function createPipeFetch(limit, dataArr) {
let _tmpFetchArr = [];
function createFetch(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data);
}, 3000)
}).then(res => {
console.log('data', data);
dataArr.length > 0 && _tmpFetchArr.push(createFetch(dataArr.shift()));
})
}
if (limit < dataArr.length) { // 如果最大并发数大于数组长度
while(limit > 0) {
_tmpFetchArr.push(createFetch(dataArr.shift()));
--limit;
}
} else {
[].concat(dataArr).forEach((item) => {
_tmpFetchArr.push(createFetch(item));
dataArr = [];
})
}
return Promise.all(_tmpFetchArr);
}
createPipeFetch(2, [1,2,3,4,5,6,7])
console