promise

Promise 是 JavaScript 中用于处理异步操作的对象,它代表一个异步操作的最终完成或失败,以及其结果值。Promise 的状态有三种:pending(进行中)、fulfilled(已成功)、rejected(已失败)。

创建 Promise 对象

复制代码
const myPromise = new Promise((resolve, reject) => {
  // 异步操作,例如从服务器获取数据
  const data = fetchDataFromServer();

  if (data) {
    // 成功时调用 resolve,并传递结果
    resolve(data);
  } else {
    // 失败时调用 reject,并传递错误信息
    reject("Failed to fetch data");
  }
});

处理 Promise 结果

复制代码
myPromise
  .then((result) => {
    // 在Promise成功时执行,result为resolve传递的值
    console.log(result);
  })
  .catch((error) => {
    // 在Promise失败时执行,error为reject传递的值
    console.error(error);
  })
  .finally(() => {
    // 无论成功或失败都会执行的代码块
    console.log("Promise completed");
  });

Promise 链

复制代码
fetchData()
  .then((data) => process1(data))
  .then((result1) => process2(result1))
  .then((result2) => {
    console.log(result2);
  })
  .catch((error) => {
    console.error(error);
  });

fetchData 返回一个 Promise 对象,然后通过 then 方法链式调用两个处理函数 process1process2。如果任何一个步骤失败,将会跳到 catch 部分。

Promise.all 和 Promise.race

复制代码
const promise1 = fetchData1();
const promise2 = fetchData2();

// Promise.all 等待所有 Promise 完成
Promise.all([promise1, promise2])
  .then((results) => {
    console.log("All promises fulfilled:", results);
  })
  .catch((error) => {
    console.error("At least one promise rejected:", error);
  });

// Promise.race 等待任何一个 Promise 完成
Promise.race([promise1, promise2])
  .then((result) => {
    console.log("The first promise fulfilled:", result);
  })
  .catch((error) => {
    console.error("The first promise rejected:", error);
  });

Promise.all 等待所有的 Promise 完成,返回一个包含所有结果的数组;Promise.race 等待任何一个 Promise 完成,返回第一个完成的结果或错误。

Promise 是一种处理异步操作的强大机制,它使得异步代码更容易理解和维护。注意,现代 JavaScript 中的 async/await 也是基于 Promise 的语法糖,更进一步简化了异步代码的编写。

相关推荐
掘金安东尼7 小时前
让 JavaScript 更容易「善后」的新能力
前端·javascript·面试
掘金安东尼7 小时前
用 HTMX 为 React Data Grid 加速实时更新
前端·javascript·面试
灵感__idea9 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
yinuo10 小时前
轻松接入大语言模型API -04
前端
袋鼠云数栈UED团队11 小时前
基于 Lexical 实现变量输入编辑器
前端·javascript·架构
cipher11 小时前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
UrbanJazzerati11 小时前
非常友好的Vue 3 生命周期详解
前端·面试
AAA阿giao11 小时前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
兆子龙12 小时前
像 React Hook 一样「自动触发」:用 Git Hook 拦住忘删的测试代码与其它翻车现场
前端·架构
兆子龙12 小时前
用 Auto.js 实现挂机脚本:从找图点击到循环自动化
前端·架构