There's a code snippet I'm working on where I need to await
5 promises, wait for 2 seconds, and then continue with another set of 5 promises. However, it seems like the two instances of Promise.all
are not being awaited as expected. I wonder if I have misunderstood the concept of Promise.all
or if there is something missing in my code.
(function () {
let val = 0
const promiseArr = []
for (let i = 0; i < 10; i++) {
promiseArr[i] = new Promise((res) => {
val += 500
setTimeout((val2) => {
console.log(val2)
res()
}, val, val)
})
}
console.log();
(async function() {
await Promise.all(promiseArr.slice(0, 5))
console.log('start await')
await new Promise((res) => setTimeout(res, 2000))
console.log('done await')
await Promise.all(promiseArr.slice(6, 10))
})()
}) ()
Expected output:
500
...
2500
start await
done await
3000
...
5000
Actual output:
500
1000
1500
2000
2500
start await
3000
3500
4000
4500
done await
5000
EDIT: After some more investigation, I realize why it behaves this way. It seems like I had a misunderstanding about an important concept involving Promises. Thanks for all the help provided!