自己实现 Promise.all()
和 Promise.race()
Promise.race_ = function(promiseList) {
if (!Array.isArray(promiseList)) throw new Error('promiseList 必须是可迭代对象');
return new Promise((resolve, reject) => {
for (const p of promiseList) {
Promise.resolve(p).then(res => resolve(res), err => reject(err));
}
});
}
Promise.all_ = function(promiseList) {
if (!Array.isArray(promiseList)) throw new Error('promiseList 必须是可迭代对象');
return new Promise((resolve, reject) => {
const promiseNum = promiseList.length;
let resovledCount = 0;
const resolvedValues = new Array(promiseNum);
promiseList.forEach((p, i) => {
Promise.resolve(p).then(res => {
resolvedValues[i] = res;
resovledCount += 1;
if (resovledCount === promiseNum) resolve(resolvedValues);
}, err => reject(err));
});
});
}
function fakePromise(url, time, success = true) {
return new Promise((resolve, reject) => {
console.log(`${url} 开始`);
setTimeout(() => {
if (success) resolve(`${url} 成功`);
else reject(`${url} 失败`);
}, time * 1000);
});
}
const promiseList = [
fakePromise('1', 2),
fakePromise('2', 3),
fakePromise('3', 1),
fakePromise('4', 2, false),
fakePromise('5', 4),
fakePromise('6', 2),
];
Promise.race_(promiseList).then(res => console.log(res), err => console.log(err));
Promise.all_(promiseList).then(res => console.log(res), err => console.log(err));