Compose async steps into a pipeline
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...ofloop withawaitis both the simplest and the correct implementation —reducewith 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.
- 1.pipes a value through every step
- 2.mixes synchronous and asynchronous steps
- 3.returns the input unchanged with no steps
- 4.stops at the first failing step
- 5.runs the steps sequentially, not in parallel
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.