Home > Article > Web Front-end > How to Synchronously Execute a Sequence of Promises in JavaScript?
In this scenario, we have an array of promise objects that must be resolved in the exact order specified in the array. Additionally, if one element is rejected, the entire chain should reject immediately, preventing further attempts at resolving subsequent elements.
Here's an example showcasing manual iteration for sequential promise execution:
function processArray(array, fn) { var index = 0; function next() { if (index < array.length) { fn(array[index++]).then(next); } } return next(); }
This function takes an array and a promise-returning function fn as arguments. It iterates through the array, calling fn on each element and passing the result to the next iteration.
function processArray(array, fn) { return array.reduce((p, item) => { return p.then(() => { return fn(item).then((data) => { results.push(data); return results; }); }); }, Promise.resolve()); }
This approach uses the reduce() method to accumulate an array of results. Each item in the array is processed sequentially, with the returned promise from fn being used to advance the iteration.
The Bluebird promise library provides convenient methods for handling asynchronous operations, including sequential iteration.
Promise.mapSeries(arr, (item) => { // process each individual item here, return a promise return processItem(item); }).then((results) => { // process final results here }).catch((err) => { // process error here });
The Promise.mapSeries() method takes an array and a promise-producing function and returns a promise that resolves to an array of resolved results.
With the ES7 async/await syntax, sequential async operations can be written in a more concise and readable manner:
async function processArray(array, fn) { let results = []; for (let i = 0; i < array.length; i++) { let r = await fn(array[i]); results.push(r); } return results; // will be resolved value of promise }
In this example, the processArray function iterates through the array, using await to pause the loop until each promise returned from fn is resolved.
The best approach for synchronizing a sequence of promises depends on factors such as the number of elements in the array, the complexity of the processing function fn, and the desired error handling behavior. For smaller arrays and simple processing functions, manual iteration or using Bluebird's Promise.mapSeries() may suffice. For more complex scenarios, using async/await or a custom solution like the one provided in the final answer may be more suitable.
The above is the detailed content of How to Synchronously Execute a Sequence of Promises in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!