以下内容会引发一个unhandledrejection
事件,但其他情况似乎“正常”。
for...await
似乎通过发出异常(尽管在第一个承诺解决之后)来响应被拒绝的承诺。
我可以使用unhandledrejection
和Promise.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()