0

I was pushing list of promises into an array, so that later i can use promise.allSettled to get result of promises but once i push promises to an array and after that i make an api call and then use promise.allSettled to get results of it, but it threw Uncaught promise first.

(async function () {
const fakeTimer = (val) => new Promise(res => setTimeout(() => res(val), 2000))
const fakeTimerError = () => new Promise((res, rej) => setTimeout(() => rej('Hello'), 300))
var arr = [1, 2, 4, 6,7, 3]
var promises = []

try {
    for (let val of arr) {
        await fakeTimer('test1')
        if (val === 4) {
            promises.push(fakeTimerError())
        } else {
            promises.push(fakeTimer(val))   
        }
    }
    const res = await Promise.allSettled(promises)
    console.log(res)
} catch (error) {
    console.log('error', error)
}
})()

Response i am getting

Image of response

1 Answers1

0

This happens because the function awaits before the promises are wrapped with allSettled(). If you call allSettled() first it works fine.

const remaining = Promise.allSettled(promises)
await fakeTimer('test1')
await fakeTimer('test2')
const res = await remaining
digby280
  • 879
  • 1
  • 7
  • 22