怎么证明真的会用Promise

86 阅读3分钟

先自评

  • then.catch的链式调用
const myPromise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve("print test1");
}, 300);
});
myPromise1
 .then((res) => {
   return res;
 })
 .then((res) => {
   console.log(res);
   return res + "test2";
 })
 .then((res) => {
   throw new Error("aaa");
 })
 .then((res) => {
   console.log("no problem");
 })
 .catch((res) => {
   console.log("there has something wrong");
   return "wrong";
 })
 .then((res) => {
   console.log(res);
 });
const myPromise2 = new Promise((resolve, reject) => {
  //   setTimeout(() => {
  //     resolve("print test1");
  //   }, 300);
  setTimeout(() => {
    reject("print test1");
  }, 300);
});
myPromise2
  .then((res) => {
    return res;
  })
  .then((res) => {
    console.log(res);
    return res + "test2";
  })
  .then((res) => {
    throw new Error("aaa");
  })
  .then((res) => {
    console.log("no problem");
  })
  .catch((res) => {
    console.log("there has something wrong");
    return "wrong";
  })
  .then((res) => {
    console.log(res);
  });
  • 封装请求超时

  • 一个页面有多个请求,请求都会成功,但结果不一定正确,获得第一个结果正确的结果 *

  • 按照指定顺序封装,有三个请求,请求a依赖请求b和请求c的结果,请求a的结果返回后调用请求d.

  • 将234问题,和async await结合使用

再学习

三种状态

Promise内部有三个状态:pending(等待中)、fulfilled(已完成)、rejected(已拒绝)。

当Promise对象被创建后,它处于pending状态,当成功执行了回调函数后,将处于fulfilled状态,如果执行失败,则处于rejected状态。

当Promise对象从pending状态变为fulfilled或rejected状态时,会触发then方法添加的成功回调函数或失败回调函数。如果Promise对象已经处于fulfilled或rejected状态,再添加回调函数也不会执行。

promise的方法使用

Promise.then(()=>{})

Promise对象具有then方法,可以添加成功回调函数和失败回调函数。这也是promise的优点,避免了回调嵌套的问题。 .then() 方法需要两个参数,第一个参数作为处理已兑现状态的回调函数,而第二个参数则作为处理已拒绝状态的回调函数。每一个 .then() 方法还会返回一个新生成的 promise 对象,这个对象可被用作链式调用,而这个then的返回值会逐级传递到下一个 .then() 中,而“reject”的结果则会被传递到链中的下一个已拒绝状态的处理函数

Promise.all([])

  • 参数:promise数组
  • 完成条件:都成功或任意一个失败
  • 结果:都成功了返回promise结果的数组,与入参一致。有一个执行失败,刚返回失败的promise

Promise.allSettled([])

  • 参数:promise数组
  • 完成条件:所有promise都执行完成
  • 结果:对应每个promise结果的数组。

Promise.any([])

  • 参数:promise数组
  • 完成条件:任意一个 promise 成功
  • 结果:成功的promise结果的数组。

Promise.race([])

  • 参数:promise数组
  • 完成条件:任意一个 promise 状态改变
  • 结果:改变状态的promise的结果。

Promise.reject(reason)

返回一个状态为已拒绝的 Promise 对象,并将失败信息返回给对应的处理函数

Promise.resolve(reason)

返回一个状态由给定 value 决定的 Promise 对象。如果结果是带有 then 方法的对象,返回的 Promise 对象的最终状态由 then 方法执行结果决定;否则,返回的 Promise 对象状态为已完成,并且将该 value 传递给对应的 then 方法。

所以,当不确定一个值是否是 promise 对象,使用 Promise.resolve(value)来返回一个 Promise 对象,这样就能把 value 以 promise 对象形式使用。