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

How to Sequence Promise Execution with Parameter Passing from an Array?

Mary-Kate Olsen
Release: 2024-10-20 14:57:02
Original
373 people have browsed it

How to Sequence Promise Execution with Parameter Passing from an Array?

Sequential Execution of Promises with Parameter Passing from an Array

Consider the scenario where you have an array of values (e.g., myArray) and need to execute a promise-based function (e.g., myPromise) sequentially, passing each array element as a parameter. How can you implement a "pauseable loop" that ensures the promises are resolved in the correct order?

Solution: Iterative Promise Execution

To achieve sequential execution, you can use a combination of promise chaining and iterative processing. Here's a code snippet demonstrating how this can be done:

myArray.reduce(
  (p, x) =>
    p.then(() => myPromise(x)),
  Promise.resolve()
)
Copy after login

This approach leverages the reduce method to iterate over the array and create a series of chained promises. Each promise is resolved after the previous promise is completed, effectively enforcing the desired sequence of execution.

Async Function Alternative

If you have support for asynchronous functions, a cleaner solution is available using the forEachSeries function:

const forEachSeries = async (iterable, action) => {
  for (const x of iterable) {
    await action(x)
  }
}

forEachSeries(myArray, myPromise)
Copy after login

This function iterates over the array and pauses at each element, waiting for the promise to be resolved before proceeding to the next iteration.

Collecting Results

If you need to collect the return values of the promises into an array, you can modify the forEachSeries function as follows:

const mapSeries = async (iterable, fn) => {
  const results = []

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

  return results
}
Copy after login

This function iterates over the array, accumulates the results of the promises in the results array, and finally returns the collected results.

The above is the detailed content of How to Sequence Promise Execution with Parameter Passing from an Array?. 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!