JavaScript中的Promise

79 阅读7分钟

一、介绍

Promise ,译为承诺,是异步编程的一种解决方案,比传统的解决方案(回调函数)更加合理和更加强大

在以往我们如果处理多层异步操作,我们往往会像下面那样编写我们的代码

doSomething(function (result) {
  doSomethingElse(
    result,
    function (newResult) {
      doThirdThing(
        newResult,
        function (finalResult) {
          console.log("得到最终结果: " + finalResult);
        },
        failureCallback
      );
    },
    failureCallback
  );
}, failureCallback);

阅读上面代码,是不是很难受,上述形成了经典的回调地狱

现在通过Promise的改写上面的代码

doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log("得到最终结果: " + finalResult);
  })
  .catch(failureCallback);

瞬间感受到promise解决异步操作的优点:

  • 链式操作减低了编码难度
  • 代码可读性明显增强

下面我们正式来认识promise

状态

promise对象仅有三种状态

  • pending(进行中)
  • fulfilled(已成功)
  • rejected(已失败)

特点

  • 对象的状态不受外界影响,只有异步操作的结果,可以决定当前是哪一种状态
  • 一旦状态改变(从pending变为fulfilled和从pending变为rejected),就不会再变,任何时候都可以得到这个结果

流程

image.png

二、用法

Promise对象是一个构造函数,用来生成Promise实例

const promise = new Promise(function(resolve, reject) {});

Promise构造函数接受一个函数作为参数,这个函数也被称为executor,代表执行器的意思,里面执行的是同步代码,该函数的两个参数分别是resolvereject

  • resolve函数的作用是,将Promise对象的状态从“进行中”变为“成功”,pending=>fulfilled
  • reject函数的作用是,将Promise对象的状态从“进行中”变为“失败”,pending=>rejected

实例方法

Promise构建出来的实例存在以下方法:

  • then()
  • catch()
  • finally()

then()

then是实例状态发生改变时的回调函数,第一个参数是resolved状态的回调函数,第二个参数是rejected状态的回调函数

then方法返回的是一个新的Promise实例,也就是promise能链式书写的原因

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
  }, 1000);
});

const newPro = promise.then((res) => {
  console.log(res); // success
});

console.log(newPro instanceof Promise); // true

catah()

catch()方法在一般情况下是.then(null, rejection).then(undefined, rejection)的替代物,为何这么说呢,来看看下面的代码

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("fail");
  }, 1000);
});

promise
  .then(
    (res) => {
      console.log(res); // 这个回调不会执行
    },
    (err) => {
      console.log("onRejected", err);  // onRejected fail
    }
  )
  .catch((err) => {
    console.log("catch", err);  // 这个回调不会执行
  });

如果reject传递到.then第二个回调(称为rejection)中,会被捕获处理,catch中的代码将不会执行,如何将rejection注释掉呢

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("fail");
  }, 1000);
});

promise
  .then(
    (res) => {
      console.log(res);  // 这个回调不会执行
    },
    // (err) => {
    //   console.log("onRejected", err);
    // }
  )
  .catch((err) => {
    console.log("catch", err);  // catch fail
  });

则promise的reject状态会传递给catch进行处理,说明了reject具有冒泡属性,如果没有一项rejection或者catch去捕获这个reject状态,最终会冒泡到顶层,抛出UncaughtException错误

另外,catch还能捕获到then()中回调函数抛出的错误

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    // reject("fail");
    resolve("success");
  }, 1000);
});

promise
  .then(
    (res) => {
      console.log(res); // success
      throw new Error("onFulfilled err");
    },
    (err) => {
      console.log("onRejected", err); // onRejected fail
      throw new Error("onRejected err");
    }
  )
  .catch((err) => {
    console.log("catch", err); // catch Error: onFulfilled err 或者 catch Error: onRejected err
  });

promise中对于错误的捕获和reject捕获行为是一样的,可以认为对rejectthrow ...的处理是一样的,这里就不做过多演示了,唯一需要注意的就是和try...catch一样,promise也不能捕获到异步代码中抛出的错误

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    throw new Error("err");  // 由于是setTimeout中执行的回调,会直接抛出错误,无法传递给then
  }, 1000);
});

promise.then(
  () => {},
  (err) => {
    console.log(err);
  }
);

一般来说,使用catch方法代替then()第二个参数

Promise 对象抛出的错误不会传递到外层代码,即不会有任何反应

const promise = new Promise((resolve, reject) => {
  resolve(x+1)
});
console.log(11111); // 还会继续执行

浏览器运行到这一行,会打印出错误提示ReferenceError: x is not defined,但是不会退出进程

catch()方法之中,还能再抛出错误,通过后面catch方法或者rejection捕获到

finally()

finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作

new Promise((resolve, reject) => {
  reject("fail");
})
  .then(null, (err) => {
    console.log("onRejected", err);
    return Promise.reject("fail");
  })
  .catch((err) => {
    console.log("catch", err);
  })
  .finally(() => {
    console.log("finally");
  });
  // onRejected fail
  // catch fail
  // finally

构造方法

Promise构造函数存在以下方法:

  • all()
  • race()
  • allSettled()
  • resolve()
  • reject()
  • try()

all()

Promise.all()方法用于将多个 Promise 实例,包装成一个新的 Promise 实例

const p = Promise.all([p1, p2, p3]);

接受一个Iterable可迭代对象(通常为数组)作为参数,数组成员都应为Promise实例

实例p的状态由p1p2p3决定,分为两种:

  • 只有p1p2p3的状态都变成fulfilledp的状态才会变成fulfilled,此时p1p2p3的返回值组成一个数组,传递给p的回调函数
  • 只要p1p2p3之中有一个被rejectedp的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数

注意,如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()catch方法,其实就是上面说明的冒泡原理

const p1 = new Promise((resolve, reject) => {
  resolve("hello");
})
  .then((res) => res)
  .catch((e) => e);

const p2 = new Promise((resolve, reject) => {
  throw new Error("报错了");
})
  .then((res) => res)
  .catch((e) => e);

Promise.all([p1, p2])
  .then((res) => console.log("onFulfilled", res))
  .catch((e) => console.log("catch", e));
// onFulfilled ["hello", Error: 报错了]

如果p2没有自己的catch方法,就会调用Promise.all()catch方法

const p1 = new Promise((resolve, reject) => {
  resolve("hello");
})
  .then((res) => res)
  .catch((e) => e);

const p2 = new Promise((resolve, reject) => {
  throw new Error("报错了");
})

Promise.all([p1, p2])
  .then((res) => console.log("onFulfilled", res))
  .catch((e) => console.log("catch", e));
// catch ["hello", Error: 报错了]

race()

Promise.race()方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例

const p = Promise.race([p1, p2, p3]);

只要p1p2p3之中有一个实例率先改变状态,p的状态就跟着改变

率先改变的 Promise 实例的返回值则传递给p的回调函数

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("p1");
  }, 1000);
})
  .then((res) => res)
  .catch((e) => e);

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("p2");
  }, 100);
})
  .then((res) => res)
  .catch((e) => e);

Promise.race([p1, p2])
  .then((res) => console.log("onFulfilled", res))
  .catch((e) => console.log("catch", e));
// onFulfilled p2

为什么这里明明是变成rejected,却还进入成功的回调函数里面呢,原因和all()中提到的一样,只要p2自己捕获了rejected,就不会传递给race,所以还是认为是成功的

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("p1");
  }, 1000);
})

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("p2");
  }, 100);
})

Promise.race([p1, p2])
  .then((ewa) => console.log("onFulfilled", res))
  .catch((e) => console.log("catch", e));
/// catch p2

allSettled()

Promise.allSettled()方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例

只有等到所有这些参数实例都返回结果,不管是fulfilled还是rejected,包装实例才会结束

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("p1");
  }, 1000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("p2");
  }, 100);
});

Promise.allSettled([p1, p2])
  .then((res) => console.log("onFulfilled", res))
  .catch((e) => console.log("catch", e));
// onFulfilled [
//   { status: 'fulfilled', value: 'p1' },
//   { status: 'rejected', reason: 'p2' }
// ]

同样的,如果各自都对自身的rejected状态进行了捕获,那allSettled()还是认为它是成功的

resolve()

将现有对象转为 Promise 对象

Promise.resolve('success') 
// 等价于 
new Promise(resolve => resolve('success'))

参数可以分成四种情况,分别如下:

  • 参数是一个 Promise 实例,promise.resolve将不做任何修改、原封不动地返回这个实例
  • 参数是一个thenable对象(即带有 then 方法),promise.resolve会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then()方法
  • 参数不是具有then()方法的对象,或根本就不是对象,Promise.resolve()会返回一个新的 Promise 对象,状态为resolved
  • 没有参数时,直接返回一个resolved状态的 Promise 对象

reject()

Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected

Promise.reject("出错了");
new Promise((resolve, reject) => reject("出错了"));

三、使用场景

  1. 将图片的加载写成一个Promise,一旦加载完成,Promise的状态就发生变化
  2. 通过链式操作,将多个渲染数据分别给个then,让其各司其职。或当下个异步请求依赖上个请求结果的时候,我们也能够通过链式操作友好解决问题
  3. 通过all()实现多个请求合并在一起,汇总所有请求结果,只需设置一个loading即可
  4. 通过race可以设置图片请求超时

......

还有许多使用场景,欢迎大家评论区留言~