Home >Web Front-end >JS Tutorial >How to Execute a Sequence of Promises in Order and Handle Rejections?
In this scenario, you need to ensure that:
While there is no direct built-in solution for this, here are ways to achieve this behavior:
Manual Iteration Using Recursion:
function sequence(arr) { const index = 0; function next() { if (index < arr.length) { arr[index]().then(next).catch(reject); index++; } } next(); }
Using Reduce:
function sequence(arr) { return arr.reduce((p, item) => { return p.then(() => item()); // Assuming each element is a promise-returning function }, Promise.resolve()); }
Using Promise.mapSeries:
If you're using the Bluebird Promise library, you can utilize its Promise.mapSeries method:
function sequence(arr) { return Promise.mapSeries(arr, item => item()); }
Using ES7 Async/Await:
If supported, you can use async/await to achieve this:
async function sequence(arr) { const results = []; for (let item of arr) { results.push(await item()); } return results; }
Using spex Library:
The spex library provides a sequence method that allows you to iterate over a sequence of dynamic promises:
import { sequence } from 'spex'; function sequence(nextPromise) { // while nextPromise() creates and returns another promise, continue resolving it; }
Remember, if any element in the array is rejected, the sequence will reject as soon as that rejection is encountered. This behavior ensures that further elements are not processed.
The above is the detailed content of How to Execute a Sequence of Promises in Order and Handle Rejections?. For more information, please follow other related articles on the PHP Chinese website!