The following emits an unhandledrejection
event, but otherwise seems to "work".
for...await
seems to respond to the rejected promise by emitting an exception (albeit after the first promise has resolved).
I can avoid the unhandledrejection
event using Promise.all
and Promise.allSettled
. Is the following code an antipattern?
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()