Skip to Content
Mastering JavaScript Functional Programming - Second Edition
book

Mastering JavaScript Functional Programming - Second Edition

by Federico Kereki
January 2020
Intermediate to advanced
470 pages
11h 13m
English
Packt Publishing
Content preview from Mastering JavaScript Functional Programming - Second Edition

Looping over async calls

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming

Federico Kereki

Publisher Resources

ISBN: 9781839213069Supplemental Content