以这种方式等待多个承诺是一种反模式吗?

Ben*_*Ben 5 javascript

以下发出一个unhandledrejection事件,但似乎“工作”。

for...await 似乎通过发出异常来响应被拒绝的承诺(尽管在第一个承诺已经解决之后)。

我可以unhandledrejection使用Promise.alland避免该事件Promise.allSettled。以下代码是反模式吗?

async function asyncFunction() {
    try {
        const happy = new Promise((resolve)=>setTimeout(()=>resolve('success'), 1000))
        const sad = new Promise((_,reject)=>setTimeout(()=>reject('failure')))
        const promises = [happy, sad]
        for await(const item of promises) {
            console.log(item)
        }
    } catch (err) {
        console.log(`an error occurred:`, err)
    }
}

asyncFunction()
Run Code Online (Sandbox Code Playgroud)