<script>
// 实现带有并发控制的promise.all,返回的结果顺序需要和传入的promise顺序一致
// myAll(promises, parallelLimit);
// myAll([promise1, promise2, promise3], 2)
const promise1 = function() {
return new Promise((resolve, reject) => {
console.log('promise1执行了');
setTimeout(() => {
console.log('promise1');
resolve(1);
}, 3000)
});
}
const promise2 = function() {
return new Promise((resolve, reject) => {
console.log('promise2执行了');
setTimeout(() => {
console.log('promise2');
resolve(2);
}, 5000)
});
}
const promise3 = function() {
console.log('promise3执行了');
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('promise3');
resolve(3);
}, 1000)
});
}
// const b = a();
// b.then(res => {
// console.log(res);
// });
// 实现带有并发控制的promise.all,返回的结果顺序需要和传入的promise顺序一致
// myAll(promises, parallelLimit);
// myAll([promise1, promise2, promise3], 2)
function myAll(promises = [], parallelLimit) {
let result = [],
runCount = 0,
queue = [];
return new Promise((resolve, reject) => {
const runPromise = (promiseFn, i) => {
if (runCount < parallelLimit) {
const promise = promiseFn();
runCount += 1;
promise.then(res => {
console.log(`promise${i + 1}完成了`);
result[i] = res;
runCount -= 1;
if (runCount === 0) {
resolve(result);
} else {
if (queue.length) {
const { promiseFn, i} = queue.shift();
runPromise(promiseFn, i);
}
}
});
} else {
queue.push({
promiseFn: promiseFn,
i: i,
})
}
};
for (let i = 0; i < promises.length; i++) {
const promiseFn = promises[i];
if (typeof promiseFn === 'function') {
runPromise(promiseFn, i);
}
}
});
// 通过队列和递归的方法实现
// return new Promise((resolve, reject) => {
// for (let i = 0; i < promises.length; i++) {
// const promiseFn = promises[i];
// if (typeof promiseFn === 'function') {
// queue.push({
// promiseFn: promiseFn,
// i: i,
// })
// }
// }
// const runPromise = () => {
// if (runCount < parallelLimit) {
// if (queue.length) {
// const { promiseFn, i} = queue.shift();
// const promise = promiseFn();
// runCount += 1;
// promise.then(res => {
// console.log(`promise${i + 1}完成了`);
// result[i] = res;
// runCount -= 1;
// if (runCount === 0) {
// resolve(result);
// } else {
// runPromise();
// }
// });
// runPromise();
// }
// }
// };
// runPromise();
// });
}
const promises = [promise1, promise2, promise3];
myAll(promises, 2).then(res => {
console.log(res);
});
</script>
网友评论