<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>
实现带有并发控制的promise.all,返回的结果顺序需要和传入的promise顺序一致
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...