插件窝 干货文章 async/await 和 .then 中如何确保所有异步操作完成后再执行后续步骤?

async/await 和 .then 中如何确保所有异步操作完成后再执行后续步骤?

Promise result error 异步 352    来源:    2025-03-20

在 JavaScript 中,处理异步操作时,确保所有异步操作完成后再执行后续步骤是一个常见的需求。你可以使用 async/await.then 两种方式来实现这一点。以下是两种方法的详细说明:

1. 使用 async/await

async/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 完成(即 resolvereject)。
  • 如果任何一个 awaitPromisereject,控制权会立即转移到 catch 块中。

2. 使用 .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 完成后执行。
  • 如果任何一个 Promisereject,控制权会立即转移到 .catch 块中。

3. 使用 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 都完成时才会完成。
  • 如果任何一个 PromiserejectPromise.all 会立即 reject,并且不会等待其他 Promise 完成。

总结

  • async/await:适合顺序执行的异步任务,代码更易读。
  • .then:适合传统的 Promise 链式调用。
  • Promise.all:适合并行执行的异步任务,提高效率。

根据你的具体需求选择合适的方法。