22. Promise 基本语法 + 错误捕获 副本.md

查看飞书原文 ↗3,754 字符

1. 核心概念 (Core Concept)

Promise 是 JavaScript 中用于处理异步操作的一种机制。它代表了一个异步操作的最终完成(或失败)及其结果值。Promise 使得异步代码更容易编写和管理,避免了回调地狱(callback hell)。

2. 为什么需要它? (The "Why")

3. API 与用法 (API & Usage)

Promise 是一个构造函数或类。

构造函数:

new Promise(executor)

实例方法:

经典代码示例 (来自 MDN / 官方文档风格):

示例 1: 基本的 Promise 承诺和解析

const myPromise = new Promise((resolve, reject) => {
  // 模拟一个异步操作,比如 setTimeout
  setTimeout(() => {
    const success = true; // 假设操作成功
    if (success) {
      resolve("操作成功完成!"); // 成功时调用 resolve
    } else {
      reject("操作失败!"); // 失败时调用 reject
    }
  }, 1000);
});

myPromise.then((result) => {
  console.log("成功:", result); // 打印 "成功: 操作成功完成!"
}).catch((error) => {
  console.error("失败:", error);
});

示例 2: Promise 链式调用和错误捕获

function step1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("步骤 1 完成");
      resolve(1);
    }, 500);
  });
}

function step2(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("步骤 2 完成,接收到值:", value);
      resolve(value + 1);
    }, 500);
  });
}

function step3(value) {
  return new Promise((_, reject) => {
    setTimeout(() => {
      console.log("步骤 3 即将失败,接收到值:", value);
      reject(new Error("步骤 3 失败了!")); // 模拟失败
    }, 500);
  });
}

step1()
  .then(step2)      // 步骤 1 的结果传递给 step2
  .then(step3)      // step2 的结果传递给 step3
  .then(finalResult => {
    console.log("所有步骤成功完成:", finalResult); // 这里的代码不会执行,因为 step3 失败了
  })
  .catch(error => {
    console.error("捕获到错误:", error.message); // 错误会被这里的 catch 捕获
  })
  .finally(() => {
    console.log("异步流程结束"); // 无论成功或失败都会执行
  });

4. 关键注意事项 (Key Considerations)

5. 参考资料 (References)


原文链接与附件索引