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 方法链式调用两个处理函数 process1 和 process2。如果任何一个步骤失败,将会跳到 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 的语法糖,更进一步简化了异步代码的编写。

相关推荐
刘发财12 分钟前
前端如何生成10000页PDF文件?
前端·javascript·开源
A接拉起0071 小时前
2026 年 JavaScript 开发者需要了解的知识
前端·javascript·后端
用户11481867894841 小时前
面试官:大屏项目里十几个模块同时渲染上万条数据,怎么做到不卡?
前端·性能优化
前端市界1 小时前
Pro React Admin: 统一工程底座,承载多种应用...
前端·github
葡萄城技术团队1 小时前
dsh-spreadjs-editor 当前支持什么:安装前需要了解的几件事
前端
三*一1 小时前
优化修整算法
前端·javascript·算法
weifont3 小时前
自动化抓取和上架商品:能不动手,就少动手
运维·前端·自动化
米柆3 小时前
HTML5 audio /video 完整事件监听模板
前端·html·html5
IT_陈寒3 小时前
Vite热更新失效?你可能也踩了这个坑
前端·人工智能·后端
程序员大阳4 小时前
副队长CSS教程(30)–CSS Grid 实战:实现复杂自适应表单布局
前端·css·自适应·grid·表单