1. PromiseAll
// 封装
Promise.prototype.all = function(promiseArray) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promiseArray)) {
return reject(new Error('传入参数必须是数组'));
}
const res = [];
const promiseNums = promiseArray.length;
let counter = 0;
for (let i = 0; i < promiseNums; i++) {
Promise.resolve(promiseArray[i]).then(value => {
counter++;
res[i] = value;
if (counter === promiseNums) {
resolve(res);
}
}).catch(e => {
reject(e);
})
}
});
}
2. PrototypeFinally
Promise.prototype.finally = function(callback) {
return this.then(res => Promise.resolve(callback()).then(() => res),
err => Promise.reject(callback()).catch(() => {throw err}));
}
PromiseAll & PrototypeFinally 使用示例
// 使用
let p = new Promise((resolve, reject) => {});
const pro1 = new Promise((res, rej) => {
setTimeout(() => {
res('1')
}, 1000)
});
const pro2 = new Promise((res, rej) => {
setTimeout(() => {
res('2')
}, 2000)
});
const pro3 = new Promise((res, rej) => {
setTimeout(() => {
res('3')
}, 3000)
});
p.all([pro1, pro2, pro3])
.then(res => {
console.log(res); // 3s后打印["1", "2", "3"]
})
.catch(e => {
console.log(e);
})
.finally(res => {
console.log('finally---'); // 打印finally---
});
p.all(1)
.then(res => {
console.log(res);
})
.catch(e => {
console.log(e); // Error: 传入参数必须是数组
})
.finally(res => {
console.log('finally---'); // 打印finally---
});
3. Promise.allSettled
Promise.all_settled = function (promises) {
return new Promise((resolve) => {
// const promises = Array.from(iterators);
if(!Array.isArray(promises)) {
resolve(new Error('传入参数必须是数组'));
}
const num = promises.length;
const resultList = new Array(num);
let resultNum = 0;
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then((value) => {
resultList[index] = { status: "fulfilled", value };
if (++resultNum === num) {
resolve(resultList);
}
})
.catch((error) => {
resultList[index] = { status: "rejected", reason: error };
if (++resultNum === num) {
resolve(resultList);
}
});
});
});
};
const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);
Promise.all_settled([resolved, rejected]).then((results) => {
console.log(results);
});
Promise.all_settled().then((results) => {
console.log(results);
});

运行结果
网友评论