Skip to the solution
MediumFrontendAsked in 20244 min read

Run Async Functions in Sequence, Each Using the Previous Result (Promise Waterfall)

1.5k views

The problem

Problem, as an interviewer would state it: "Write waterfall(tasks, initial) — run an array of async functions one after another, each receiving the PREVIOUS one's result as its own input, returning the final result."

Examples:

Code
await waterfall([addOne, double, toString], 5);
// addOne(5)=6 -> double(6)=12 -> toString(12)="result: 12"

Clarifying questions expected:

  • Does this genuinely need to run sequentially, or would running everything in parallel and just chaining the DATA dependency be acceptable?
  • What happens if one task in the middle rejects — does the whole waterfall stop?
  • Is the very first task's input always the same as the overall initial value passed in?

Code / implementation expected: Yes — real, direct proof via a logged execution order that this is genuinely sequential, not just producing the correct final chained result by coincidence.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a promise waterfall produces the correct chained result and is verified genuinely sequential via a real logged execution order

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 75 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Query String Generator

Continue