Promise 用法分享

151 阅读4分钟

Promise

Promise 是异步编程的一种解决方案。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。Promise是一个容器,保存着将来可能会发生的事情,从它可以获取异步操作的消息。

promise有3种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操作决定结果,其他操作无法改变。一旦新建便立即执行,无法取消。

const promise = new Promise(function (resolve, reject) {
    // ... some code

    if (/* 异步操作成功 */) {
        resolve(value);
    } else {
        reject(error);
    }
});
promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。

Promise 原型链上的方法:

  • Promise.prototype.then()
  • Promise.prototype.catch()
  • Promise.prototype.finally()

Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。

finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。 finally方法的回调函数不接受任何参数,这意味着没有办法知道,前面的 Promise 状态到底是fulfilled还是rejected。这表明,finally方法里面的操作,应该是与状态无关的,不依赖于 Promise 的执行结果。

举个🌰

const promise = new Promise(function(resolve, reject) {
  resolve('ok');
  throw new Error('test');
});
promise
  .then(function(value) { console.log(value) })
  .catch(function(error) { console.log(error) });
// ok

Promise 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。

Promise.resolve()返回一个新的 Promise 实例,该实例的状态为resolve;

Promise.reject()返回一个新的 Promise 实例,该实例的状态为rejected

Promise.all()

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

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

Promise.all()方法接受一个数组作为参数,p1、p2、p3都是 Promise 实例,如果不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。另外,Promise.all()方法的参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。

p的状态由p1、p2、p3决定,只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数,只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

const p1 = new Promise((resolve, reject) => {
  resolve('p1成功了');
})

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

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

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

如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

const p1 = new Promise((resolve, reject) => {
  resolve('p1成功了');
})
.then(result => result)
.catch(e => e);

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

const p3 = new Promise((resolve, reject) => {
  throw new Error('p3报错了');
})
.then(result => result)
.catch(e => e);

Promise.all([p1, p2, p3])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["p1成功了", Error: p2报错了, Error: p3报错了]

Promise.race()

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

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

上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

const p1 = new Promise((resolve, reject) => {
  // ... some code
  resolve('p1成功了');
})

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error('request timeout')), 5000)
})

Promise.race([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// p1成功了

Promise.allSettled()

Promise.allSettled()方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例。只有等到所有这些参数实例都返回结果,不管是fulfilled还是rejected,包装实例才会结束。该方法由 ES2020 引入。

const p1 = Promise.resolve(42);
const p2 = Promise.reject(-1);

Promise.allSettled([p1, p2])
.then(results => console.log(results));
// [
//    { status: 'fulfilled', value: 42 },
//    { status: 'rejected', reason: -1 }
// ]

Promise.any()

Promise.any()方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例。只要参数实例有一个变成fulfilled状态,包装实例就会变成fulfilled状态;如果所有参数实例都变成rejected状态,包装实例就会变成rejected状态。该方法目前是一个第三阶段的提案 。

const p1 = Promise.resolve(0);
const p2 = Promise.reject(-1);
const p3 = Promise.reject(-2);

Promise.any([p1, p2, p3])
.then(result => console.log(result))
.catch(e => console.log(e));
// 0

Promise.any([p2, p3])
.then(result => console.log(result))
.catch(e => console.log(e));
// AggregateError: All promises were rejected

Promise.try()

不知道或者不想区分,函数f是同步函数还是异步操作,但是想用 Promise 来处理它。因为这样就可以不管f是否包含异步操作,都用then方法指定下一步流程,用catch方法处理f抛出的错误。

const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// now

const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next