Home >Web Front-end >JS Tutorial >How to Execute Promises Sequentially for Dynamic Arrays?
When working with arrays, it's often necessary to execute a series of tasks for each element sequentially, passing parameters between 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.
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>
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>
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!