January 2020
Intermediate to advanced
470 pages
11h 13m
English
Finally, finding an equivalent for reduce() is a bit more complex, but after the other functions that we've seen, not so much. The key idea is the same as in forEachAsync: each function call will return a promise, which must be awaited in order to update the accumulator in an upcoming then(). To do the reducing, let's have a fakeSum() async function that will just sum the API-returned values:
const reduceAsync = (arr, fn, init) => Promise.resolve(init).then(accum => forEachAsync(arr, async (v, i) => { accum = await fn(accum, v, i); }).then(() => accum) );const fakeSum = (value1, value2) => new Promise(resolve => setTimeout(() => resolve(value1 + value2), 1000));(async () => { console.log("START REDUCE"); const summed ...Read now
Unlock full access