乐闻世界logo
搜索文章和话题

How can I execute array of promises in sequential order?

1个答案

1

When handling multiple asynchronous operations, executing a Promise array in sequence is a common requirement. This can be achieved in various ways, such as using the async/await syntax or chaining execution with the then() method of Promise. I will now describe both methods separately and provide examples.

Method One: Using async/await

The async/await approach is a modern way to handle asynchronous operations, allowing us to write asynchronous code in a synchronous manner, making it clearer and more understandable. Using this approach, we can iterate over the Promise array using a for loop within an async function and use await to wait for each Promise to resolve.

javascript
async function sequentialStart(promises) { const results = []; for (const promise of promises) { const result = await promise(); results.push(result); } return results; } // Example: Define three asynchronous tasks const promise1 = () => new Promise(resolve => setTimeout(() => resolve('Result 1'), 1000)); const promise2 = () => new Promise(resolve => setTimeout(() => resolve('Result 2'), 500)); const promise3 = () => new Promise(resolve => setTimeout(() => resolve('Result 3'), 100)); // Using the function sequentialStart([promise1, promise2, promise3]).then(console.log); // Output: ['Result 1', 'Result 2', 'Result 3']

Method Two: Chaining with then() Method

In this method, we use the reduce() method of the array to chain each Promise. The initial value is a resolved Promise, and at each step, we use then() to combine the previous result with the next Promise.

javascript
function chainPromises(promises) { return promises.reduce((chain, currentPromise) => { return chain.then(chainResults => currentPromise().then(currentResult => [...chainResults, currentResult]) ); }, Promise.resolve([])); } // Using the same example chainPromises([promise1, promise2, promise3]).then(console.log); // Output: ['Result 1', 'Result 2', 'Result 3']

Summary

Both methods can effectively execute a Promise array in sequence. The async/await method provides more concise and intuitive code, while the then() method is a more traditional approach that can flexibly handle various asynchronous operation patterns. In actual development, you can choose the appropriate method based on specific circumstances.

2024年6月29日 12:07 回复

你的答案