在 JavaScript 中,处理异步操作时,确保所有异步操作完成后再执行后续步骤是一个常见的需求。你可以使用 async/await 和 .then 两种方式来实现这一点。以下是两种方法的详细说明:
async/awaitasync/await 是 ES2017 引入的语法糖,它使得异步代码看起来更像同步代码,更容易理解和维护。
async function runAsyncTasks() {
try {
const result1 = await asyncTask1();
const result2 = await asyncTask2();
const result3 = await asyncTask3();
console.log('All tasks completed:', result1, result2, result3);
} catch (error) {
console.error('An error occurred:', error);
}
}
runAsyncTasks();
await 关键字会暂停 async 函数的执行,直到 Promise 完成(即 resolve 或 reject)。await 的 Promise 被 reject,控制权会立即转移到 catch 块中。.then.then 是传统的 Promise 链式调用方式,适用于 ES6 及更早的版本。
asyncTask1()
.then(result1 => {
return asyncTask2().then(result2 => [result1, result2]);
})
.then(([result1, result2]) => {
return asyncTask3().then(result3 => [result1, result2, result3]);
})
.then(([result1, result2, result3]) => {
console.log('All tasks completed:', result1, result2, result3);
})
.catch(error => {
console.error('An error occurred:', error);
});
.then 都会在前一个 Promise 完成后执行。Promise 被 reject,控制权会立即转移到 .catch 块中。Promise.all如果你有多个独立的异步任务,并且希望它们并行执行,可以使用 Promise.all。
async function runAsyncTasksInParallel() {
try {
const [result1, result2, result3] = await Promise.all([
asyncTask1(),
asyncTask2(),
asyncTask3()
]);
console.log('All tasks completed:', result1, result2, result3);
} catch (error) {
console.error('An error occurred:', error);
}
}
runAsyncTasksInParallel();
Promise.all 接受一个 Promise 数组,并返回一个新的 Promise,该 Promise 在所有输入的 Promise 都完成时才会完成。Promise 被 reject,Promise.all 会立即 reject,并且不会等待其他 Promise 完成。async/await:适合顺序执行的异步任务,代码更易读。.then:适合传统的 Promise 链式调用。Promise.all:适合并行执行的异步任务,提高效率。根据你的具体需求选择合适的方法。