Home  >  Article  >  Web Front-end  >  How to Execute Promises Sequentially for Dynamic Arrays?

How to Execute Promises Sequentially for Dynamic Arrays?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 14:58:30491browse

How to Execute Promises Sequentially for Dynamic Arrays?

Executing Promises Sequentially with Dynamically Populated Arrays

When working with arrays, it's often necessary to execute a series of tasks for each element sequentially, passing parameters between promises.

Sequential Execution of Promises

To achieve this, one can use a nested series of .then() calls. However, as the array size increases, this approach becomes cumbersome and inflexible.

Fold Reduction with Reduce

A concise solution is to use the .reduce() method to fold the array into a series of promises:

<code class="js">const promiseChain = myArray.reduce(
  (p, x) => p.then(() => myPromise(x)),
  Promise.resolve()
);</code>

Async Functions for Looping

A more maintainable approach is to use an async function that iterates through the array and executes each promise sequentially:

<code class="js">const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x);
  }
};

forEachSeries(myArray, myPromise);</code>

Collecting Return Values

If the return values of the promises are needed, a slight modification of the mapSeries function can be employed:

<code class="js">const mapSeries = async (iterable, fn) => {
  const results = [];

  for (const x of iterable) {
    results.push(await fn(x));
  }

  return results;
};</code>

This approach provides greater flexibility and code readability when handling dynamic arrays of promises.

The above is the detailed content of How to Execute Promises Sequentially for Dynamic Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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