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 的语法糖,更进一步简化了异步代码的编写。

相关推荐

  1. promise

    2024-01-23 13:50:04       58 阅读
  2. Promise

    2024-01-23 13:50:04       53 阅读
  3. Promise

    2024-01-23 13:50:04       41 阅读
  4. <span style='color:red;'>Promise</span>

    Promise

    2024-01-23 13:50:04      36 阅读
  5. Promise

    2024-01-23 13:50:04       19 阅读
  6. Promise介绍

    2024-01-23 13:50:04       49 阅读
  7. Promise实现

    2024-01-23 13:50:04       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-23 13:50:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-23 13:50:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-23 13:50:04       82 阅读
  4. Python语言-面向对象

    2024-01-23 13:50:04       91 阅读

热门阅读

  1. 测试经理面试初体验

    2024-01-23 13:50:04       58 阅读
  2. Linux查找日志常用命令

    2024-01-23 13:50:04       53 阅读
  3. GitLab备份与恢复测试(基于Docker)

    2024-01-23 13:50:04       63 阅读
  4. MCS-51指令格式

    2024-01-23 13:50:04       44 阅读
  5. 消息队列面试系列-02

    2024-01-23 13:50:04       51 阅读
  6. 牛客竞赛算法入门题单打卡 J Keep in Line

    2024-01-23 13:50:04       57 阅读