Promise.all方法
// promise all
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(11);
}, 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(22);
}, 2000);
});
// Promise.all([p1, p2]).then(res => {
// console.log(res);//(2) [11, 22] "r===="
// }).catch(err => {
// console.log(err);
// })
function myPromiseAll(list) {
return new Promise((resolve, reject) => {
let resultsArr = [];
let num = 0;
list.forEach((item) => {
item.then((res) => {
resultsArr.push(res);
num++;
if (num == list.length) {
resolve(resultsArr);
}
});
});
});
}
myPromiseAll([p1, p2])
.then((r) => {
console.log(r, "r====");//(2) [11, 22] "r===="
})
.catch((err) => {
console.log(err);
});
使用promise.all
如果有一个对象reject
了,那么promise.all
就会返回错误,promise.all
只能返回全部是resolve
的结果
Promise.allSettled方法
let p3 = new Promise((resolve,reject)=>{
// resolve(11)
reject("error======")
})
let p4 = new Promise((resolve,reject)=>{
resolve(222)
})
Promise.allSettled([p3,p4]).then(res=>{
console.log(res);
//0: {status: "rejected", reason: "error======"}
//1: {status: "fulfilled", value: 222}
})
使用promise.allSettled
的话,不管是否是reject
都会返回,并且返回成功或者失败的status
网友评论