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决定,分成两种情况。
(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
下面示例:
1、给各个promise添加catch
let x = 10;let p1 = new Promise((resolve) => {resolve("p1 hello" + x);}).then((res) => {console.log(`p1 then 输出${res}`);return res;}).catch((e) => {console.log("p1 报错了");console.log(e);});let p2 = new Promise((resolve) => {resolve("p2 hello" + x);}).then((res) => {console.log(`p2 then 输出${res}`);return res;}).catch((e) => {console.log("p2 报错了");console.log(e);});let p3 = new Promise((resolve) => {resolve("p3 hello" + x);}).then((res) => {console.log(`p3 then 输出${res}`);return res;}).catch((e) => {console.log("p3 报错了");console.log(e);});let p4 = new Promise((resolve) => {resolve("p4 hello" + x);}).then((res) => {console.log(`p4 then 输出${res}`);return res;}).catch((e) => {console.log("p4 报错了");console.log(e);});Promise.all([p1, p2, p3, p4]).then(result => console.log(result)).catch((e) => {console.log("f*cking man 报错了");console.log(e);});
输出:
2、去掉变量x
,会报异常,各个Promise中的catch捕捉到对应的异常, Promise.all中的catch不起效:
// let x = 10;let p1 = new Promise((resolve) => {resolve("p1 hello" + x);}).then((res) => {console.log(`p1 then 输出${res}`);return res;}).catch((e) => {console.log("p1 报错了");console.log(e);});let p2 = new Promise((resolve) => {resolve("p2 hello" + x);}).then((res) => {console.log(`p2 then 输出${res}`);return res;}).catch((e) => {console.log("p2 报错了");console.log(e);});let p3 = new Promise((resolve) => {resolve("p3 hello" + x);}).then((res) => {console.log(`p3 then 输出${res}`);return res;}).catch((e) => {console.log("p3 报错了");console.log(e);});let p4 = new Promise((resolve) => {resolve("p4 hello" + x);}).then((res) => {console.log(`p4 then 输出${res}`);return res;}).catch((e) => {console.log("p4 报错了");console.log(e);});Promise.all([p1, p2, p3, p4]).then(result => console.log(result)).catch((e) => {console.log("f*cking man 报错了");console.log(e);});
输出结果:
3、去掉各个promise的catch:
// let x = 10;let p1 = new Promise((resolve) => {resolve("p1 hello" + x);}).then((res) => {console.log(`p1 then 输出${res}`);return res;});let p2 = new Promise((resolve) => {resolve("p2 hello" + x);}).then((res) => {console.log(`p2 then 输出${res}`);return res;});let p3 = new Promise((resolve) => {resolve("p3 hello" + x);}).then((res) => {console.log(`p3 then 输出${res}`);return res;});let p4 = new Promise((resolve) => {resolve("p4 hello" + x);}).then((res) => {console.log(`p4 then 输出${res}`);return res;});Promise.all([p1, p2, p3, p4]).then(result => console.log(result)).catch((e) => {console.log("f*cking man 报错了");console.log(e);});
输出结果