Promise + async/await 的结合使用, 也是现代 JavaScript 异步编程的核心写法!

// ======================== 定义异步任务 1:遛狗 ========================
function walkDog() {
  // 返回一个 Promise 对象,表示“异步任务的结果”
  return new Promise((resolve, reject) => {
    // 用 setTimeout 模拟异步操作(延迟 1.5 秒)
    setTimeout(() => {
      const dogwalked = true; // ✅ 模拟任务成功(改成 false 可测试失败)
      if (dogwalked) {
        resolve("🐶 You walked the dog."); // 成功 → 调用 resolve()
      } else {
        reject("❌ You didn’t walk the dog."); // 失败 → 调用 reject()
      }
    }, 1500);
  });
}
 
// ======================== 定义异步任务 2:打扫厨房 ========================
function cleanKitchen() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const kitchenCleaned = true; // ✅ 模拟成功
      if (kitchenCleaned) {
        resolve("🍽️ You cleaned the kitchen.");
      } else {
        reject("❌ You didn’t clean the kitchen.");
      }
    }, 2500);
  });
}
 
// ======================== 定义异步任务 3:倒垃圾 ========================
function takeOutTrash() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const trashTakenOut = false; // ❌ 模拟失败
      if (trashTakenOut) {
        resolve("🗑️ You took out the trash.");
      } else {
        reject("❌ You didn’t take out the trash.");
      }
    }, 500);
  });
}
 
// ======================== 使用 async/await 顺序执行任务 ========================
// async 关键字表示这个函数内部可以使用 await
async function doChores() {
  try {
    // 使用 await 等待 Promise 完成(相当于同步执行的写法)
    const walkDogResult = await walkDog(); // 等 walkDog() 完成
    console.log(walkDogResult);             // 输出结果
    const cleanKitchenResult = await cleanKitchen(); // 再等 cleanKitchen 完成
    console.log(cleanKitchenResult);
    const takeOutTrashResult = await takeOutTrash(); // 最后等 takeOutTrash 完成
    console.log(takeOutTrashResult);
  }
  catch (error) {
    // 如果上面任意一个 Promise 被 reject,直接跳到这里
    console.log(error);
  }
}
  • async:让函数返回一个 Promise(自动包装)。
  • await:暂停函数执行,直到 Promise 完成
  • 如果 Promise 成功 → 返回 resolve 的值;
  • 如果 Promise 失败 → 抛出错误,被 catch 捕获。
关键词作用对应 Promise 写法
async声明一个异步函数,返回 Promise隐式返回 Promise
await暂停执行直到 Promise 完成等价于 .then()
try…catch捕获异步错误等价于 .catch()

promise 和 async/await 的区别:

async/await 本质上是写 Promise 的更简洁方式。

对比点Promiseasync/await
写法风格链式调用 .then()、.catch()像同步代码一样,用 await 顺序执行
可读性稍显复杂(多层 then 链)非常直观(从上往下读)
错误处理.catch(error) 捕获错误try…catch 块捕获错误
调试难度链式回调中断点不好打调试更直观,像同步逻辑
底层机制Promise 对象的回调链执行使用 Promise,但通过 await 语法“暂停”执行
返回值.then() 返回新的 Promiseasync 函数自动返回 Promise
//两者功能一样
// promise 写法
walkDog()
  .then(result => {
    console.log(result);
    return cleanKitchen();
  })
  .then(result => {
    console.log(result);
    return takeOutTrash();
  })
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.log(error);
  });
 
// async/await 写法
  async function doChores(){
  try {
    const walk = await walkDog();
    console.log(walk);
 
    const clean = await cleanKitchen();
    console.log(clean);
 
    const trash = await takeOutTrash();
    console.log(trash);
  }
  catch(error){
    console.log(error);
  }
}