对Promise简单的理解

Promise是什么

  • 一个对象(一个函数返回的对象)

Promise 可以做什么

  • 把最终的成功的返回值或失败原因和相应的处理程序联系起来,避免出现回调地狱

如何使用Promise

创建Promise

cosnt p = new Promise(resolve,reject)
  • 它包含俩个参数一个成功的回调resolve,一个失败的回调reject

Promise的三个状态

  • pending:待定(初始状态)
  • fulfilled 完成
  • rejected 失败
    只能从pending—>fulfilled或pending—>rejected,一经执行,不在改变
const p1 = new Promise((resolve, reject) => {
   resolve("成功");
   reject("失败");
 }).then((res) => {
   console.log(res, "res");
 });
 const p2 = new Promise((resolve, reject) => {
   reject("失败");
   resolve("成功");
 }).catch((err) => {
   console.log(err, "err");
 });
  • 上述代码中p1中的reject和p2中的resolve不在执行

then方法

  • then方法本身会返回一个promise对象
  • 接收俩个参数,一个成功的回调,一个失败的回调
  • Promise状态为fulfilled执行成功回调,rejected执行失败回调

链式调用

  • 可以通过链式调用then、catch来处理和接收成功或失败回调的内容
 const p1 = new Promise((resolve, reject) => {
 	resolve("成功");
 }).then((res) => {
   console.log(res, "res");
 });
 const p2 = new Promise((resolve, reject) => {
   reject("失败");
 }).catch((err) => {
   console.log(err, "err");
 });
// 成功 res
// 失败 err

连续链式调用

new Promise((resolve, reject) => {
  console.log("初始化");
  resolve();
})
  .then((result) => {
    throw new Error("抛出错误");
    console.log("执行这个"); // 因为上面抛出错误,所以此行不执行
  })
  .catch((err) => {
    console.log(err, "执行catch");
  })
  .then((res) => {
    console.log(res, "finally");
  });

多个链式调用一般会在最后调用catch

Promise.all

  • 用于并行处理多个异步请求
const request1 = () => {
   return new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve({
         state: 1,
         data: [{ id: 1, name: 1 }],
       });
     }, 1000);
   });
 };
 const request2 = () => {
   return new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve({
         state: 1,
         data: [{ userId: 1, userName: "lili" }],
       });
     }, 1000);
   });
 };
 Promise.all([request1(), request2()]).then((res) => {
   console.log(res, "res");
 });

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值