Home  >  Article  >  Web Front-end  >  How to Sequence Promise Execution with Parameter Passing from an Array?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 14:57:02377browse

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()
)

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)

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
}

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!

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