Home > Web Front-end > JS Tutorial > body text

How to Execute Promises Sequentially for Dynamic Arrays?

Barbara Streisand
Release: 2024-10-20 14:58:30
Original
490 people have browsed it

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

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

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

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!

source:php
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!