Async Waterfall

MediumPromises & Async15 min5 tests

Implement waterfall(fns) that executes async functions in sequence, passing each result as input to the next.

Requirements

  • fns is 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 === 4
Hints (5)
  1. Use a loop (for or reduce) to iterate through the functions.
  2. Call the first function with no arguments.
  3. Pass the result of each function as the argument to the next.
  4. Use await to handle both sync and async return values.
  5. Return the final result.

Topics

  • Promises & Async

Asked at

Microsoft · Amazon · Atlassian

Join Us
blur