31 01 2019
How to use async/await with forEach ( oneliner )
forEach
is not working for asynced functions. In that case you might start doing old style for loops or even for-of loops.
Also if you have a bluebird package already installed you can use bluebird.each()
instead. In ECMAScript 2018 there is going to be asynchronous iteration, but for those who stuck on older versions I have oneliner, which i use, if i don’t want to install bluebird or other promise library.
Definition of each
:
const each = (arr, cb, i = 0) => i < arr.length ? Promise.resolve(cb(arr[i++])).then(() => each(arr, cb, i)) : Promise.resolve();
await each(['a', 'b', 'c'], async(item) => {
console.log('this is ', item);
await new Promise(resolve => setTimeout(resolve, 1000));
});
What you see is NOT what you get useEffectlessState for data fetching with React hooks