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

时间:2020-03-16 11:16:32

标签: javascript

以下内容会引发一个unhandledrejection事件,但其他情况似乎“正常”。

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

我可以使用unhandledrejectionPromise.all来避免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()

0 个答案:

没有答案