Promise all 并发处理1.0版本。

```js


const fn = function (time) {
return () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(Date.now() + ':' + time);
resolve(time);
}, time * 1000);
})
}
}

const fnArray = [];
for (let i = 0; i < 10; i += 1) {
fnArray.push(fn(i));
}

const schedule = async (fnArray, limit) => {
const dataReult = [];
const runStack = [...fnArray];
let startNewIndex = limit - 1;
const run = async (fn, index, retry = 3 ) => {

if (index > fnArray.length - 1 ){
return;
}

if (startNewIndex > fnArray.length - 1 ){
return;
}

if (!retry) {
dataReult[index] = -1;
return;
}

try {
const data = await fn();
dataReult[index] = data;
} catch (err) {
console.error(err);
return run(fn, index, retry--);
}

startNewIndex++;
 
const newFn = runStack[startNewIndex];
const newRetry = 3;
return run(newFn, startNewIndex, newRetry)
}
 
const fns = [];
for (let i = 0; i < limit; i++) {
fns.push(run(fnArray[i], i, 3));
}
await Promise.all(fns);

console.log(dataReult);
}

schedule(fnArray, 2);
 

```

posted on 2022-05-01 21:38  偏灬爱  阅读(38)  评论(0编辑  收藏  举报

导航