Home >Web Front-end >JS Tutorial >How to Sequence Promise Execution 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?
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.
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.
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!