Promise.allSettled = function (list) {
if (list instanceof Array) {
let ret = [];
list.forEach((i) => {
ret.push(
new Promise(function (resolve, reject) {
i.then((v) => {
resolve({ state: true, data: v });
}).catch((e) => {
resolve({ state: false, data: e });
});
})
);
});
return Promise.all(ret);
}
return Promise.reject();
};
// 简单测试
function rand() {
return new Promise(function (resolve, reject) {
let ret = parseInt(Math.random() * 100);
console.log(ret, ret % 1)
if (ret%2 === 0) {
resolve(ret);
} else {
reject(ret);
}
});
}
// test
let list = [];
for (let i = 10; i > 0; i--) {
list.push(rand());
}
Promise.allSettled(list).then(v => console.log(v))
网友评论