The reduce() function is a powerful tool. Reduce((promise, fn) => promise.then(fn), Promise.resolve()) In the end, `res` is equivalent to // `Promise.resolve().then(fn1).then(fn2).then(fn3)` const res = await functions. Chain the function calls in order, starting with an empty promise. There is a non-standard ries functionįor this, but you can also do this with reduce(). Suppose you have an array of async functions that you want to execute in series. function sum( arr) ) Bonus: Promise Chaining Here's how you might sum up an array with a plain old for loop. Most reduce() tutorials start with this example: given an array of numbers, calculate the sum. Here are 4 common examples and 1 not-so-common example that demonstrate how to use reduce(). Of confusion, but it can also make your code much more readable when combined with other functional programming abstractions. The reduce() method on JavaScript arrays executes a "reducer" function on everyĮlement of the array in order, passing the return value from the previous reducerĬall to the next reducer call.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |