Async Waterfall
MediumPromises & Async15 min5 tests
Implement waterfall(fns) that executes async functions in sequence, passing each result as input to the next.
Requirements
fnsis an array of functions. The first takes no arguments; each subsequent one receives the result of the previous.- Each function may return a value or a Promise.
- Return the result of the last function.
- If any function throws, reject immediately.
Example
const result = await waterfall([
() => 1,
(x) => x + 1,
(x) => Promise.resolve(x * 2)
]);
// result === 4Hints (5)
- Use a loop (for or reduce) to iterate through the functions.
- Call the first function with no arguments.
- Pass the result of each function as the argument to the next.
- Use await to handle both sync and async return values.
- Return the final result.
Topics
- Promises & Async
Asked at
Microsoft · Amazon · Atlassian
