January 2020
Intermediate to advanced
470 pages
11h 13m
English
Since async calls return promises, we can emulate forEach() with reduce() by starting with a resolved promise and chaining to it the promises for each value in the array. The then() methods will be called in the right order, so the results will be correct. The following piece of code manages to get the right, expected results:
const forEachAsync = (arr, fn) => arr.reduce( (promise, value) => promise.then(() => fn(value)), Promise.resolve() );(async () => { console.log("START FOREACH VIA REDUCE"); await forEachAsync([1, 2, 3, 4], async n => { const x = await fakeAPI(n * 1000, n); useResult(x); }); console.log("END FOREACH VIA REDUCE");})();/*START FOREACH VIA REDUCE2019-10-13T20:02:23.437Z 12019-10-13T20:02:24.446Z ...