个人学习笔记 - Promise.all和Promise.race用法及差异

76 阅读1分钟

Promise.all()

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

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

Promise.all()方法的参数是具备Iterator接口的类型,且参数中每个成员都是Promise实例,若成员为非Promise实例,会先调用Promise.resolve()方法,状态为resolved
Promise.all()形成的新实例具备两种状态:

  1. 参数成员的状态都为fullfilled,新实例状态为fullfilled,所有成员实例的返回值组成数组作为新实例的返回值
  2. 参数成员有一个状态为rejected,新实例的状态就为rejected,第一个被reject的实例返回值会作为新实例的返回值
const p1 = fPromiseCreate(1);  //fullfilled
const p2 = p1.then(res => res);  //fullfilled
const p3 = 'success';  //fullfilled

const z1 = fPromiseCreate(1);  //fullfilled
const z2 = fPromiseCreate(0);  //rejected
const z3 = z2.catch(res => res);  //rejected

const p = Promise.all([p1, p2, p3]);
const z = Promise.all([z1, z2, z3]);

function fPromiseCreate(probability) {
    let flag = probability > 0 ? true : false;
    return new Promise((resolve, reject) => {
        flag ? resolve('success') : reject(new Error('error!'));
    });
};

console.log('p',p);
console.log('z',z);
p.then(res => console.log(res));
z.catch(res => console.log(res))


//p {Promise}
//z {Promise}
//Error:error!
//['success', 'success', 'success']

Promise.race()

区别于Promise.all()优先改变状态的成员实例将作为新实例的状态,且返回值传递给新实例

let probability = Math.ceil(Math.random() * 10) * 1000;
const p1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('success'), 5000)
});
const p2 = new Promise((resolve, reject) => {
    setTimeout(() => reject('Error'), probability)
});
const p = Promise.race([p1, p2]);
p.then(res => console.log(res))
 .catch(err => console.log(err));
console.log('p',p)
console.log('probability',probability)

//p Promise
//probability 2000
//Error