promise.all 返回一个promise,then的结果要和promise.all输入的结果顺序一致。若有reject,则按promise.all 输入的顺序,第一个reject被弹出。
/**
* 实现一个 promise.all()
*/
Promise.all1 = function (promises) {
let results = new Array();
return new Promise(async function (resolve, reject) {
promises.forEach(promise => {
promise.then(res => {
results.push(res);
if (results.length === promises.length) {
resolve(results);
}
});
});
});
}
const a = new Promise(function (resolve, reject) {
resolve('a resolve');
});
const b = new Promise(function (resolve, reject) {
resolve('b resolve');
});
const c = new Promise(function (resolve, reject) {
reject('c reject');
});
// Promise.all([a, b])
// .then(res => {
// console.log(res);
// })
// .catch(err => {
// console.warn(err);
// });
Promise.all1([a, b, c])
.then(res => {
console.log(res, '000');
})
.catch(err => {
console.log(err, 'iiii');
});
精品句子
何不策高足,先据要路津。 — 《少年派》语录
3分钟,了解天下大事
每天花3分钟在【每日全搜索】上,可尽知天下大事。
把省下来的时间留给自我技术沉淀噻~