Reduce an array to chained promises
suggest changeWhen asynchronous operations must run sequentially, a for...of loop with await is usually clearer than constructing a promise chain with reduce(). The loop below is top-level await in a module, or the body of an async function:
for (const value of [1, 3, 5, 7, 9]) {
console.log(value);
await new Promise(resolve => setTimeout(resolve, 1_000));
}
console.log('done');
The reduction patterns below remain useful when an expression must construct the chain or when working in non-async code.
There are two variants :
- the “then” reduction, which builds a chain that continues as long as the chain experiences success.
- the “catch” reduction, which builds a chain that continues as long as the chain experiences error.
The “then” reduction
This variant of the pattern builds a .then() chain, and might be used for chaining animations, or making a sequence of dependent HTTP requests.
[1, 3, 5, 7, 9].reduce((seq, n) => {
return seq.then(() => {
console.log(n);
return new Promise(res => setTimeout(res, 1000));
});
}, Promise.resolve()).then(
() => console.log('done'),
(e) => console.log(e)
);
// will log 1, 3, 5, 7, 9, 'done' in 1s intervals
Explanation:
- We call
.reduce()on a source array, and providePromise.resolve()as an initial value. - Every element reduced will add a
.then()to the initial value. reduce()’s product will be Promise.resolve().then(…).then(…).- We manually append a
.then(successHandler, errorHandler)after the reduce, to executesuccessHandleronce all the previous steps have resolved. If any step was to fail, thenerrorHandlerwould execute.
Unlike Promise.all(), which starts with promises that may already be running concurrently, this reduction invokes each operation only after the preceding step fulfills.
The “catch” reduction
This variant of the pattern builds a .catch() chain and might be used for sequentially probing a set of web servers for some mirrored resource until a working server is found.
const working_resource = 5; // one of the values from the source array
[1, 3, 5, 7, 9].reduce((seq, n) => {
return seq.catch(() => {
console.log(n);
if(n === working_resource) { // 5 is working
return new Promise((resolve, reject) => setTimeout(() => resolve(n), 1000));
} else { // all other values are not working
return new Promise((resolve, reject) => setTimeout(reject, 1000));
}
});
}, Promise.reject()).then(
(n) => console.log('success at: ' + n),
() => console.log('total failure')
);
// will log 1, 3, 5, 'success at: 5' at 1s intervals
Explanation:
- We call
.reduce()on a source array, and providePromise.reject()as an initial value. - Every element reduced will add a
.catch()to the initial value. reduce()’s product will bePromise.reject().catch(...).catch(...).- We manually append
.then(successHandler, errorHandler)after the reduce, to executesuccessHandleronce any of the previous steps has resolved. If all steps were to fail, thenerrorHandlerwould execute.
Native Promise.any() is the concurrent counterpart: it fulfills with the first successful input and rejects with AggregateError only when every input rejects. The reduction above probes candidates sequentially instead.