【js】Promise上的一些方法

怼怼

Promise

三种状态

  1. pending 初始状态
  2. fulfilled 成功状态
  3. rejected 拒绝状态

初始状态

let p = new Promise(() => {})
console.log(p);

image.png

成功状态

let p = new Promise((resolve) => {
    resolve()
})
console.log(p);

image.png

拒绝状态

let p = new Promise((resolve, reject) => {
    reject()
})
console.log(p);

image.png

单一状态与状态中转

单一状态:Promise的状态变为fulfilled或resolved不会再改变

let p = new Promise((resolve, reject) => {
    resolve()
    reject()
})
console.log(p);

image.png

状态中转:resolve()接收一个Promise时会按照接收的状态传递

let rej = new Promise((resolve, reject) => {
    reject()
})
let p = new Promise((resolve, reject) => {
    resolve(rej)
})
console.log(rej);
console.log(p);

image.png

方法

  1. then
  2. catch
  3. finally
  4. done
  5. resolve
  6. reject
  7. all
  8. allSettled
  9. race
  10. any
  11. try

1.then(callback1,callback2)

接收resolve或reject的返回值,根据不同状态调用回调函数
then返回的也是Promise,处理后fulfilled,报错为rejected

let p = new Promise((resolve, reject) => {
    reject("拒绝")
})
let p1 = p.then(null, res => {
    console.log(res);
})
console.log(p1);

image.png

  • then返回一个Promise可以继续处理

    new Promise((resolve, reject) => {
      reject("拒绝")
    }).then(null, err => {
      console.log(err);
      return err
    }).then(err => {
      console.log(err);
    })
    //拒绝
    //拒绝

    2.catch

    等价于 .then(null,rejection) 用于指定发生错误时的回调函数

    new Promise((resolve, reject) => {
      try {
          throw new Error('错误');
      }
      catch (e) {
          reject(e)
      }//等价于 reject(new Error("错误"))
    }).then(val => {
      console.log(val);
    }).catch(res => {
      console.log(res);
    })

    image.png

  • catch捕获try中抛出的错误,然后由reject改变状态并传递
  • 错误具有"冒泡性质",会向下传递,直到被catch捕获
  • 支持then处理resolve,catch处理reject,catch可以去捕获then中的错误,类似于try/catch的写法
  • resolve后再抛出错误不会被捕获,也不会传递到外层代码

    new Promise((resolve, reject) => {
      resolve("接受")
      throw new Error('错误');
    }).then(val => {
      console.log(val); //接受
    }).catch(res => {
      console.log(res);
    })

3.finally

无论Promise对象最后状态是fulfilled还是rejected,都会执行其中的回调函数
finally的实现:

Promise.prototype.finally = function (callback) {
    let P = this.constructor
    return this.then(
        value => P.resolve(callback()).then(()=>value),
        reason => P.resolve(callback()).then(()=>{throw reason})
    )
}
new Promise((resolve, reject) => {
    reject("错误")
}).finally(() => {
    console.log(1); //1
}).catch(res => {
    console.log(res);//错误
})
  • 可以看出finally执行一个普通的回调函数,状态会向下传递

4.done

最后的错误无法捕获,可以用done抛出一个全局错误
done的实现

Promise.prototype.done = function (onFulfilled,onRejected) {
    this.then(onFulfilled,onRejected)
    .catch(function(reason){
        setTimeout(()=>{throw reason},0)
    })
}
new Promise((resolve, reject) => {
    reject(0)
}).done(val => {
    console.log(val);
}, res => {
    console.log(res);
})
  • done也可以像then一样使用

5.Promise.resolve() 与 Promise.reject()

将一个对象转为Promise对象
以Promise.resolve(参数)为例

Promise.resolve("foo")
//等价于
new Promise(resolve => resolve("foo"))
  • 参数为Promise的实例
  • Promise.resolve将不做任何修改

    let p = new Promise((resolve, reject) => {
      reject("错误")
    })
    let p1 = Promise.resolve(p)
    console.log(p1);

    image.png

  • 参数是一个thenable对象,有then方法的对象
  • Promise.resolve()会将这个对象转成Promise对象
  • 然后立即执行thenable中的then方法

    let thenable = {
      then: function (resolve, reject) {
          resolve("接受")
      }
    }
    Promise.resolve(thenable)
      .then(val => {
          console.log(val);//接受
      })
  • 参数没有then方法或不是对象
  • Promise.resolve()返回一个新的Promise对象,状态为fulfilled

    let obj = {
      a: 0
    }
    Promise.resolve(obj)
      .then(val => {
          console.log(val.a);//a
      })
  • 任何参数
  • 直接返回一个fulfilled状态的Promise对象

    Promise.resolve()
      .then(() => {
          console.log("接受状态");//接受转态
      })
    Promise.reject()也会返回一个新的Promise实例,状态为rejected
    与Promise.resolve()不同的是,Promise.reject()的参数会原封不动的传递

6.Promise.all()与Promise.allSettled()

  • Promise.all可以将多个Promise实例包装成一个新的Promise实例
  • 如果不是则会调用Promise.resolve方法,转为Promise实例
  • 参数为iterable类型
  • Promise.all返回的Promise的状态取决于参数的状态,全部fulfilled为fulfilled,有一个rejected返回第一个rejected

    let p1 = Promise.resolve("成功")
    let p2 = "foo"
    let p3 = Promise.reject("失败1")
    let p4 = Promise.reject("失败2")
      .catch(res => {
          console.log("自己的" + res);//自己的失败2
          return res
      })
    
    Promise.all([p1, p2, p4])
      .then(val => {
          console.log(val);//["成功","foo","失败2"]
      })
    
    Promise.all([p2, p4, p3])
      .then(val => {
          console.log(val);
      })
      .catch(res => {
          console.log("all的" + res);//all的失败1
      })
  • 参数有自己的catch时,状态为fulfilled
  • 参数中有一个rejected则会调用all上的catch
  • Promise.allSettled会返回所有参数的状态与返回值

    let p1 = Promise.resolve("成功")
    let p2 = "foo"
    let p3 = Promise.reject("失败1")
    let p4 = Promise.reject("失败2")
      .catch(res => {
          console.log("自己的" + res);
          return res
      })
    Promise.allSettled([p1, p2, p4])
      .then(val => {
          console.log(val);
      })
    Promise.allSettled([p2, p4, p3])
      .then(val => {
          console.log(val);
      })

    image.png

7.Promise.race()

  • 相较于Promise.all Promise.race会返回一个fulfilled或rejected的参数
  • Promise.race返回的Promise的状态由跑的最快的Promise决定的

    let p1 = new Promise((resolve, reject) => {
      setTimeout(resolve, 1000, "p1接受")
    })
    let p2 = new Promise((resolve, reject) => {
      setTimeout(reject, 1500, "p2拒绝")
    })
    
    Promise.race([p1, p2])
      .then(val => {
          console.log(val);//p1接受
      })
      .catch(res => {
          console.log(res);
      })

    8.Promise.any()

  • Promise.any正好与Promise.all相反,有一个fulfilled状态就为fulfilled

    let p1 = new Promise((resolve, reject) => {
      setTimeout(resolve, 2000, "p1接受")
    })
    let p2 = new Promise((resolve, reject) => {
      setTimeout(reject, 1500, "p2拒绝")
    })
    let p3 = new Promise((resolve, reject) => {
      setTimeout(resolve, 1000, "p3接受")
    })
    Promise.any([p1, p2, p3])
      .then(val => {
          console.log(val);//p3接受
      })
      .catch(res => {
          console.log(res);
      })
  • 如果全部为rejected则会抛出一个全部拒绝的错误

    Promise.any([p2])
      .then(val => {
          console.log(val);
      })
      .catch(res => {
          console.log(res);//AggregateError: All promises were rejected
      })

9.Promise.try()

让同步函数同步执行
两种实现方式

//方式一
Promise.try = function (func) {
    return (async () => func())()
}
//方式二
Promise.try = function (func) {
    return new Promise((resolve, reject) => {
        resolve(func())
    })
}
  • func()如果是同步函数立即执行,如果是异步函数会将返回值或错误交给then处理

    let f = () => console.log("now");
    Promise.try(f)
    console.log("next");
    //now
    //next
阅读 235
37 声望
1 粉丝
0 条评论
你知道吗?

37 声望
1 粉丝
文章目录
宣传栏