有时间把限制并发加上
<script>
let p1 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p1-成功');
}, );
});
let p2 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p2-成功');
}, 1000);
});
let p3 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p3-成功');
}, 1200);
});
let p4 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p4-成功');
}, 1400);
});
let p5 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p5-成功');
}, 4000);
});
let p6 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p6-成功');
}, 4000);
});
let p7 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p7-成功');
}, 4000);
});
let p8 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p8-成功');
}, 4000);
});
let p9 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p9-成功');
}, 4000);
});
let p10 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p10-成功');
}, 4000);
});
let p11 = new Promise(function (resolve, reject) {
setTimeout(function () {
reject('p11-成功');
}, 4000);
});
let pArr = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11]
function promiseAll(arr, limit = 5) {
if (!Array.isArray(arr)) {
throw new Error('请传入数组')
}
let newArr = [...arr]
let arrLength = arr.length
let finish = 0;
let resArr = [];
let executing = [];
return new Promise((resolve, reject) => {
newArr.forEach((item, index) => {
Promise.resolve(item.then(res => {
finish++
resArr.push({
content: res,
index
})
console.log(resArr)
if (finish == arrLength) {
resolve(resArr.sort((a, b) => a.index - b.index))
}
}).catch(err => {
reject(err)
}))
})
})
}
promiseAll(pArr).then(res => {
console.log('promiseAll 成功', res)
}).catch(err => {
console.log('promiseAll 失败', err)
})
</script>
|