Home > Web Front-end > JS Tutorial > How to Synchronously Execute a Sequence of Promises in JavaScript?

How to Synchronously Execute a Sequence of Promises in JavaScript?

DDD
Release: 2024-11-06 22:15:02
Original
323 people have browsed it

How to Synchronously Execute a Sequence of Promises in JavaScript?

How to Synchronize a Sequence of Promises?

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.

Manual Iteration

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();
}
Copy after login

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.

Using .reduce() with Promise

function processArray(array, fn) {
  return array.reduce((p, item) => {
    return p.then(() => {
      return fn(item).then((data) => {
        results.push(data);
        return results;
      });
    });
  }, Promise.resolve());
}
Copy after login

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.

Using Bluebird Promise Library

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
});
Copy after login

The Promise.mapSeries() method takes an array and a promise-producing function and returns a promise that resolves to an array of resolved results.

Using ES7 async/await

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
}
Copy after login

In this example, the processArray function iterates through the array, using await to pause the loop until each promise returned from fn is resolved.

Choosing the Right Approach

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template