promise = an object that manages asynchronous operations.

  • warp a promise object around {asynchronous code}
  • “i promise to return a value”
  • pending resolved or rejected new Promise((resolve, reject) => {saynchronous code}) 👉 把“异步任务(setTimeout)”包装在一个 可成功(resolve)失败(reject) 的对象中, 从而实现 更优雅的异步顺序执行
// ======================== 定义第一个异步任务:遛狗 ========================
function walkDog() {
  // 返回一个新的 Promise 对象
  return new Promise((resolve, reject) => {
    // 模拟耗时操作(例如异步请求),延迟 1.5 秒后执行
    setTimeout(() => {
      const dogwalked = true; // ✅ 假设遛狗成功(可改为 false 测试失败情况)
      if (dogwalked) {
        // 调用 resolve() 表示任务成功完成
        resolve("🐶 You walked the dog.");
      } else {
        // 调用 reject() 表示任务失败
        reject("❌ You didn't walk the dog.");
      }
    }, 1500);
  });
}

resolve(value) → 成功时触发 .then() reject(error) → 失败时触发 .catch()

// ======================== 第二个异步任务:打扫厨房 ========================
function cleanKitchen() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const kitchenCleaned = false; // ❌ 模拟失败(设置为 true 可成功)
      if (kitchenCleaned) {
        resolve("🍽️ You cleaned the kitchen.");
      } else {
        reject("❌ You didn't clean the kitchen.");
      }
    }, 2500);
  });
}
 
// ======================== 第三个异步任务:倒垃圾 ========================
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);
  });
}

链式调用

// ======================== Promise 链式调用 ========================
// 第一步:执行 walkDog()
walkDog()
  // 如果成功,执行第一个 then()
  .then(value => {
    console.log(value);           // 输出成功信息 "You walked the dog."
    return cleanKitchen();        // 返回下一个 Promise,继续链式执行
  })
  // 第二步:执行 cleanKitchen()
  .then(value => {
    console.log(value);           // 输出 "You cleaned the kitchen."
    return takeOutTrash();        // 返回第三个 Promise
  })
  // 第三步:执行 takeOutTrash()
  .then(value => {
    console.log(value);           // 输出 "You took out the trash."
    console.log("✅ You finished all tasks!");
  })
  // 如果任何一个任务失败,则进入 catch()
  .catch(error => {
    console.log(error);           // 输出第一个 reject() 触发的错误信息
  });

🧠 详细执行逻辑: 1️⃣ walkDog() 返回一个 Promise,1.5秒后 resolve() → 进入第一个 .then() 2️⃣ .then() 返回 cleanKitchen() 的 Promise 3️⃣ 如果厨房打扫失败(reject()),后续 .then() 全部跳过,直接进入 .catch() 4️⃣ 如果全部成功,最后会输出 ”✅ you finished all tasks”

Promise 的核心思维模型:

状态说明如何触发
pending等待中默认状态
fulfilled已完成调用 resolve(value)
rejected已失败调用 reject(error)
Promise 是一个“未来某一时刻返回结果的容器”。
它让异步操作像同步逻辑一样整齐可读,
而 .then() 和 .catch() 则是它沟通结果的桥梁。