JavaScript-异步编程之Promise

Promise 是 JavaScript 中用于处理异步操作的对象,它表示一个可能会在未来完成或失败的操作。Promise 有三个状态:pending(进行中)、fulfilled(已完成)、rejected(已拒绝)。

1. 创建 Promise

使用 Promise 构造函数来创建 Promise。它接受一个执行器函数,该函数有两个参数:resolvereject,分别用于完成和拒绝 Promise。

const myPromise = new Promise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve("Operation succeeded!");
    } else {
      reject("Operation failed!");
    }
  }, 2000);
});

2. Promise 的状态

Promise 可以处于三种状态之一:

  • pending: 初始状态,既不是成功状态,也不是失败状态。
  • fulfilled: 操作成功完成。
  • rejected: 操作失败。
myPromise.then(
  (result) => {
    console.log("Fulfilled:", result);
  },
  (error) => {
    console.error("Rejected:", error);
  }
);

3. Promise 链

Promise 支持链式调用,这样可以更容易地管理多个异步操作。

const asyncOperation = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Async operation completed.");
    }, 1000);
  });
};

asyncOperation()
  .then((result) => {
    console.log(result);
    return "Next step";
  })
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

4. Promise.all

Promise.all 接受一个包含多个 Promise 的可迭代对象,返回一个新的 Promise,该 Promise 在所有输入 Promise 完成时才被完成。

const promise1 = Promise.resolve("Promise 1");
const promise2 = new Promise((resolve) => setTimeout(() => resolve("Promise 2"), 2000));

Promise.all([promise1, promise2])
  .then((results) => {
    console.log("All promises fulfilled:", results);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

5. Promise.race

Promise.race 接受一个包含多个 Promise 的可迭代对象,返回一个新的 Promise,该 Promise 在第一个输入 Promise 完成时被完成。

const promise1 = new Promise((resolve) => setTimeout(() => resolve("Promise 1"), 1000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve("Promise 2"), 2000));

Promise.race([promise1, promise2])
  .then((result) => {
    console.log("First promise fulfilled:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

6. Promise 的错误处理

使用 catch 方法或在 then 方法的第二个参数中处理错误。

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = false;
    if (success) {
      resolve("Operation succeeded!");
    } else {
      reject("Operation failed!");
    }
  }, 2000);
});

myPromise
  .then((result) => {
    console.log("Fulfilled:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

7. 异步函数中使用 Promise

Promise 与异步函数(async/await)搭配使用,提供更清晰的异步代码结构。

function asyncOperation() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Async operation completed.");
    }, 1000);
  });
}

async function performOperations() {
  try {
    const result = await asyncOperation();
    console.log(result);
  } catch (error) {
    console.error("Error:", error);
  }
}

performOperations();
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[猫玖]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值