promise的常用情况

常规用法

function pro(params) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (params) {
                resolve(2222);
            } else {
                reject(1111);
            }
        }, 2000)
    })
}
pro(false).then((res => {
    console.log(res)
})).catch((aaa) => {
    console.log(aaa)
})

执行顺序,实例化时立即执行

let promise = new Promise(function(resolve, reject) {
    console.log('Promise');
    resolve();
  });
  promise.then(function() {
    console.log('resolved.');
  });
  console.log('Hi!');
当resolve参数是另一个promise的实例的时候会等待参数中的promis状态改变后才会执行
const p1 = new Promise(function (resolve, reject) {
    console.log(1)
    setTimeout(() => reject(new Error('fail')), 3000)
})
const p2 = new Promise(function (resolve, reject) {
    console.log(2)
    resolve(p1)
})
p2
    .then(result => console.log(result))
    .catch(error => console.log(error))

promise.all

let a = new Promise((resolve, reject) => {
    resolve(11)
})
let b = new Promise((resolve, reject) => {
    resolve(22)
})
let c = new Promise((resolve, reject) => {
    resolve(33)
})
console.log(a)
Promise.all([a, b, c]).then((res) => {
    console.log(res)
}).catch(res => {
    console.log(res)
})
//如果上边都是resolve则在then中的生效了,结果是一个数组形式
//[11,22,33]
let a = new Promise((resolve, reject) => {
    resolve(11)
})
let b = new Promise((resolve, reject) => {
    reject(22)
})
let c = new Promise((resolve, reject) => {
    reject(33)
})
Promise.all([a, b, c]).then((res) => {
    console.log(res)
}).catch(res => {
    console.log(res)
})
//如果上边其中一个不是resolve的话那then就不会执行,catch中获取到的是第一个reject的结果
//22

 Promise.race()

只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数
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);
使用场景:设置等待时长,如果请求或操作在一定时间内没有完成就返回reject状态来标识失败

Promise.allSettled()

let a = new Promise((resolve, reject) => {
    resolve(11)
})
let b = new Promise((resolve, reject) => {
    reject(22)
})
let c = new Promise((resolve, reject) => {
    resolve(33)
})
Promise.allSettled([a, b, c]).then((res) => {
    console.log(res,1)
}).catch(res => {
    console.log(res,2)
})
[
    { status: 'fulfilled', value: 11 },
    { status: 'rejected', reason: 22 },
    { status: 'fulfilled', value: 33 }
  ] 1
只有then中的打印生效了,而且输出的是一个对象形式,对象中包含了promise返回的状态
posted @ 2020-05-21 10:07  下一页2013  阅读(240)  评论(0编辑  收藏  举报