Promise

Promise

  1. Promise有三种状态:pending(进行中),fulfilled(成功),rejected(失败)
  2. 只能从pending到fulfilled,或者从pending到rejected
  3. Promise参数的不同:
  • 参数是Promise实例,Promise.resolve不做修改返回实例
  • 参数是一个thenable对象(拥有then方法的对象),Promise.resolve方法会把对象转为Promise对象,并立即执行thenable对象的then方法。
  • 参数不具有then,返回一个新的Promise对象,状态为resolved.
  • 不带任何参数,返回一个带有resolved状态的Promise对象
//setTimeout()会在事件循环开始时执行,Promise.resolve()会在循环结束时执行

//对于resolve()来说会返回一个新的Promise实例,实例的状态为resolved
setTimeout(function () {
  console.log('three');
}, 0);
Promise.resolve().then(function () {
  console.log('two');
});
console.log('one');
// one
// two
// three

Promise.reject()

返回一个新的Promise实例,状态为rejected。

Promise.try()

想要不区分f是同步还是异步操作,用then来指定下一步流程,用catch来处理f抛出的错误,然后不区分得使用Promise来处理他:

Promise.resolve().then(f)

如果想让同步直接执行,异步异步执行:

(async () => f())()
.then(...)
//可以捕获错误:
(async () => f())()
.then(...)
.catch(...)
//另一种方式是使用new Promise()
const f = () => console.log('now');
(
  () => new Promise(
    resolve => resolve(f())
  )
)();
console.log('next');
// now
// next
//使用Promise.try()
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next

对于reject和resolve没必要在后面继续执行代码,直接return

new Promise((resolve, reject) => {
  return resolve(1);
  // 后面的语句不会执行
  console.log(2);
})
//状态依赖:一个的状态依赖于另一个Promise
const p1 = new Promise(function (resolve, reject) {
  // ...
});
const p2 = new Promise(function (resolve, reject) {
  // ...
  resolve(p1);
})

使用链式的then来按照一组次序来执行,前一个then会把返回的另结果放进下一个then的回调函数中

抛出错误:

const promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});
//如果先使用catch,则会跳过,如果有多个catch,后面的会捕获前面的catch抛出的错误。
Promise.resolve()
.catch(function(error) {
  console.log('oh no', error);
})
.then(function() {
  console.log('carry on');
});
// carry on

Promise.all()

//将多个Promise实例包装成一个Promise
//只有所有的状态变成fulfilled,p的状态才是fulfilled,只要其中一个被rejected,p的状态就变成rejected
const p = Promise.all([p1, p2, p3]);

Promise.race()将多个Promise实例包装成一个

//有一个实例率先改变状态的话,p的状态就会跟着改变
const p = Promise.race([p1, p2, p3]);
const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)
  })
]);
p
.then(console.log)
.catch(console.error);

Promise.allSettled()

接受一组Promise作为参数,返回一个新的Promise实例,等它们结束返回结果时包装实例才会结束。

Promise.any()

只要一个参数实例变成了fulfilled状态,实例就会变成fulfilled状态,如果所有参数实例变成rejected状态,包装实例就会变成rejected状态。

posted @ 2022-10-19 15:53  梦呓qwq  阅读(25)  评论(0编辑  收藏  举报