AniUI Academy

Compose async steps into a pipeline

mediumAsync & Promises+250 XPPractice

Upload a file, then resize it, then persist a record, then return the URL. Written with nested .then() calls it becomes a staircase; as a pipeline it reads as a list of named steps.

Implement pipeAsync(...fns). It returns a function that takes one input value and passes it through every step from left to right, awaiting each step's result before calling the next. Steps may be synchronous or return promises. It resolves with the final value. With no steps at all it resolves with the input unchanged. If a step throws or rejects, reject with that reason and do not call any later step.

Arguments

...fnsArray<(value: any) => any | Promise>
The sequence of steps, applied left to right.

Returns

(input: any) => Promise<any> — A function that takes one input and resolves with the final value after every step has run.

Examples

const run = pipeAsync(
  async (n) => n + 1,
  async (n) => n * 10,
  async (n) => "total:" + n
);
const result = await run(2);
// result === "total:30"

Each step receives the awaited result of the previous one.

const run = pipeAsync(
  (text) => text.trim(),           // sync
  async (text) => text.toUpperCase() // async
);
await run("  hello  "); // === "HELLO"

Steps may be sync or async; both work.

What it has to do

  • Apply the steps left to right, one at a time.
  • Await each step before starting the next.
  • Support steps that return a plain value as well as a promise.
  • Resolve with the input unchanged when there are no steps.
  • Reject on the first failing step and skip the rest.

Notes

  • A for...of loop with await is both the simplest and the correct implementation — reduce with promises works too but reads worse.
  • With no steps the pipeline resolves with its input unchanged, which keeps callers from having to guard the empty case.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.