Q16: Implement an Async Waterfall Sequencer

Build an async pipeline helper that executes an array of asynchronous functions sequentially, passing the output of each function as input to the next.

Sequential Async Pipeline
function asyncWaterfall(tasks, initialValue) {
  return tasks.reduce((promiseChain, currentTask) => {
    return promiseChain.then(result => currentTask(result));
  }, Promise.resolve(initialValue));
}

const add2 = async (x) => x + 2;
const mult3 = async (x) => x * 3;

asyncWaterfall([add2, mult3], 5).then(console.log); // (5 + 2) * 3 = 21
💡 Array.reduce builds a continuous Promise chain where each task executes only after the previous task resolves.
Key Takeaways
  • Chains Promise resolution steps sequentially using Array.prototype.reduce.
  • Executes asynchronous pipeline processing, passing forward computed outcomes.
Knowledge Check

How does asyncWaterfall guarantee sequential execution over concurrent Promise.all execution?