Proper Asynchronous Loops in Javascript
I see this in PRs and catch myself doing it a lot, so putting this out here for my own reference.
Loops in Javascript will not wait for awaits before moving on to the next item or moving out of the loop entirely.
The easiest way I've found to get around this is to collect the promises from each iteration into an array via _.map, and then await Promise.all to make sure each iteration has completed before moving on.
const _ = require('underscore'); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
async function wrong() {
_.forEach([1,2,3], async function (i) { await sleep(1000); console.log(i);});
console.log('done');
};
wrong();
async function right() {
await Promise.all(_.map([1,2,3], async function (i) { await sleep(1000); console.log(i);}));
console.log('done');
};
right();
Reference: https://underscorejs.org
Comments
Post a Comment