JavaScriptFundamental (ES6), part 2
Async pipeline with reduce in JavaScript
48 A pipeline, and the reduce that looks like one
fairThread an order through three async steps, each one using the last one's output. Write it with reduce over then and again with a plain loop. Then show two things that are not pipelines: mapping the steps in parallel, and an async reducer whose accumulator is never awaited.
Stuck? Three hints, smallest first
- 1.
fns.reduce((acc, fn) => acc.then(fn), Promise.resolve(input))builds the chain without running anything twice. - 2. In parallel every step sees the original input, so their outputs cannot see each other.
- 3. Inside an
asyncreducer the accumulator is a promise. Adding to it without awaiting stringifies it.
const order = { ref: 'LAG-0048', subtotal: 24000, area: 'lekki' };
const trace = [];
const steps = [
async (o) => { trace.push('vat'); return { ...o, vat: Math.round(o.subtotal * 0.075) }; },
async (o) => { trace.push('delivery'); return { ...o, delivery: o.area === 'lekki' ? 1500 : 800 }; },
async (o) => { trace.push('total'); return { ...o, total: o.subtotal + o.vat + o.delivery }; },
];
const pipe = (fns) => (input) => fns.reduce((acc, fn) => acc.then(fn), Promise.resolve(input));
const runInOrder = async (fns, input) => {
let acc = input;
for (const fn of fns) acc = await fn(acc);
return acc;
};
const piped = await pipe(steps)(order);
const traceFromPipe = trace.slice();
const looped = await runInOrder(steps, order);
// Not a pipeline: every step gets the original order, so nothing composes.
const inParallel = await Promise.all(steps.map((fn) => fn(order)));
const parallelKeys = inParallel.map((o) => Object.keys(o).slice(3));
const awaited = await [1, 2, 3].reduce(async (sum, n) => (await sum) + n, Promise.resolve(0));
const forgotten = await [1, 2, 3].reduce(async (sum, n) => sum + n, Promise.resolve(0));
let stepsRun = 0;
const failing = [
async (n) => { stepsRun++; return n + 1; },
async () => { stepsRun++; throw new Error('rate lookup failed'); },
async (n) => { stepsRun++; return n * 100; },
];
const stopped = await pipe(failing)(1).then(() => 'finished', (err) => err.message);
const unchanged = await pipe([])(order);
console.log('piped :', piped.total, 'from', traceFromPipe);
console.log('parallel:', parallelKeys);
console.log('reduce :', awaited, 'vs', forgotten);
console.log('stopped :', stopped, 'after', stepsRun, 'steps');
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.
test('the pipeline threads each output into the next step', piped, { ref: 'LAG-0048', subtotal: 24000, area: 'lekki', vat: 1800, delivery: 1500, total: 27300 });
test('and runs them in array order, one at a time', traceFromPipe, ['vat', 'delivery', 'total']);
test('the plain loop produces exactly the same thing', looped, piped);
test('mapping in parallel gives three partial orders instead of one', parallelKeys, [['vat'], ['delivery'], ['total']]);
test('an async reducer works when the accumulator is awaited', awaited, 6);
test('and stringifies the promise when it is not, losing every earlier step', forgotten, '[object Promise]3');
test('a failing step stops the pipeline, so the third never runs', [stopped, stepsRun], ['rate lookup failed', 2]);
test('an empty pipeline hands the input straight back', unchanged, order);
Sequential and parallel are not styles, they are a question about the data. Each step here needs the field the previous one added, so they must run in order — the fourth assertion is what parallelism does to a pipeline: three objects, each holding one of the three fields, none of them a complete order. Independent work is the opposite case, and Promise.all is right there instead, as exercise 26 argues at length.
reduce over then is worth recognising because you will read it. It builds the whole chain in one synchronous pass and starts nothing extra: each acc.then(fn) is the promise the next step is attached to. The loop version is easier to read and does the same thing, so prefer it unless you actually want the composed function pipe gives you.
The sixth assertion is the trap. Inside an async reducer the accumulator is always a promise, so sum + n adds a number to a promise, JavaScript coerces the promise to ‘[object Promise]’, and nothing throws. Look closely at what survives: ‘[object Promise]3’, the last step only, because each round concatenated onto a freshly stringified promise and discarded what came before. A total that is silently wrong beats an exception for time spent debugging. (await sum) + n is the fix; a plain loop is the better fix, because there is nothing to forget.
The last two are the ordinary contract of a pipeline: a failure stops it where it happened, with the steps after it unrun, and an empty list of steps is the identity function rather than an error.