Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

pipe and compose with async functions in JavaScript

130 pipe and compose, with async steps

hard

Write pipeAsync(...steps) that threads a value through steps which may be async or plain, by reducing over then. Build a vendor lookup from four small steps, keep a trail of which ones ran, and prove that a rejection in the middle stops the rest. Then write composeAsync and show it is the same pipeline written backwards.

Stuck? Three hints, smallest first
  1. 1. Start from Promise.resolve(input) and reduce: (acc, step) => acc.then(step). That is the whole implementation.
  2. 2. then accepts a function that returns a plain value, so a synchronous step needs no wrapping and no await.
  3. 3. composeAsync is pipeAsync with the list reversed. Reverse a copy: reverse mutates.

The answer

const pipeAsync = (...steps) => (input) =>
  steps.reduce((acc, step) => acc.then(step), Promise.resolve(input));
const composeAsync = (...steps) => pipeAsync(...[...steps].reverse());

const DIRECTORY = { 'mama nkechi': { lga: 'Ikeja', kobo: 50000 } };
const trail = [];
const step = (name, fn) => async (value) => {
  trail.push(name);
  return fn(value);
};

const normalise = step('normalise', (s) => s.trim().toLowerCase());
const lookup = step('lookup', (slug) => DIRECTORY[slug] ?? null);
const required = step('required', (row) => {
  if (!row) throw new Error('vendor not found');
  return row;
});
const priced = step('priced', (row) => ({ ...row, naira: row.kobo / 100 }));

const findVendor = pipeAsync(normalise, lookup, required, priced);

const found = await findVendor('  Mama Nkechi ');
const trailWhenFound = [...trail];
trail.length = 0;

let failure = 'no error';
try { await findVendor('Unknown Trader'); } catch (e) { failure = e.message; }
const trailWhenLost = [...trail];
trail.length = 0;

const backwards = composeAsync(priced, required, lookup, normalise);
const alsoFound = await backwards('MAMA NKECHI');
trail.length = 0;

const inc = async (n) => n + 1;
const dbl = async (n) => n * 2;
const bothWays = [await pipeAsync(inc, dbl)(5), await composeAsync(inc, dbl)(5)];
const mixed = await pipeAsync((n) => n + 1, async (n) => n * 3)(2);
const emptyPipe = pipeAsync()(3);

console.log('found  :', found);
console.log('trails :', trailWhenFound, trailWhenLost);
console.log('ways   :', bothWays, '| mixed sync and async:', mixed);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the pipeline resolves to the last step\'s value', found, { lga: 'Ikeja', kobo: 50000, naira: 500 });
test('every step ran, left to right', trailWhenFound, ['normalise', 'lookup', 'required', 'priced']);
test('a throw inside a step becomes a rejection of the whole pipeline', failure, 'vendor not found');
test('and the steps after it never ran', trailWhenLost, ['normalise', 'lookup', 'required']);
test('compose is the same steps written right to left', alsoFound, found);
test('so the order genuinely matters, and the two disagree', bothWays, [12, 11]);
test('a plain function mixes in with no wrapping, because then accepts one', mixed, 9);
test('and a pipeline of nothing still hands back a promise', [typeof emptyPipe.then, await emptyPipe], ['function', 3]);

reduce over then is the smallest async pipeline there is, and it gets three things right for free. A synchronous step needs no special case, because then already accepts a function returning a plain value. A thrown error anywhere becomes one rejection of the whole chain, so there is a single place to catch. And starting from Promise.resolve(input) means the return type is always a promise, even for zero steps — a caller never has to check.

The trail is the part worth keeping in a real system. Short-circuiting is the correct behaviour, but it is also invisible: something failed and four later steps silently did not happen. Recording which steps ran is the difference between a log line you can act on and "vendor not found" with no idea how far it got.

The direction assertion is not pedantry. pipe(inc, dbl) and compose(inc, dbl) read almost the same and differ by one reversal, and mixing them up produces a plausible wrong number rather than an error. Pick one convention per codebase; pipe tends to win because it reads in the order things happen. Note this chain is strictly sequential — each step waits for the last. Steps that are independent want Promise.all, not a pipe.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.