I am having hard time in understanding how for...of
differ from .forEach()
in case of handling Promises.
Using this snippet:
const allSettled = async arr => {
const data = []
for (const promise of arr) {
try {
const result = await promise;
data.push(result);
} catch (e) {
data.push(e)
}
}
return data
}
I go over each promise in array, wait for it to settle and push the result to data
. It executes sequentially.
If I have this snippet:
const badAllSettled = arr => {
const data = []
arr.forEach(async promise => {
try {
const result = await promise;
data.push(result);
} catch (e) {
data.push(e)
}
})
return data
}
I get empty array (because forEach
does not wait for Promise to settle).
AFAIK for...of
works with iterables, hence it might suspend and wait await
to return. But how this flow works step-by-step I don't understand.
Thanks!