我试图建立一个下载自动重试下载。基本上是一个任务队列,它重试任务一定次数。我第一次尝试使用
Promise.all()
described here
没有帮助(并且是一个反模式,如该线程中进一步描述的)
所以我有一个版本的工作,似乎有点做我想要的。至少它打印的结果是正确的。但它仍然抛出几个
uncaught exception test X
asd = async () => {
// Function simulating tasks which might fail.
function wait(ms, data) {
return new Promise( (resolve, reject) => setTimeout(() => {
if (Math.random() > 0.5){
resolve(data);
} else {
reject(data);
}
}, ms) );
}
let tasks = [];
const results = [];
// start the tasks
for ( let i = 0; i < 20; i++) {
const prom = wait(100 * i, 'test ' + i);
tasks.push([i, prom]);
}
// collect results and handle retries.
for ( let tries = 0; tries < 10; tries++){
failedTasks = [];
for ( let i = 0; i < tasks.length; i++) {
const task_idx = tasks[i][0];
// Wait for the task and check whether they failed or not.
// Any pointers on how to improve the readability of the next 6 lines appreciated.
await tasks[i][1].then(result => {
results.push([task_idx, result])
}).catch(err => {
const prom = wait(100 * task_idx, 'test ' + task_idx);
failedTasks.push([task_idx, prom])
});
}
// Retry the tasks which failed.
if (failedTasks.length === 0){
break;
} else {
tasks = failedTasks;
}
console.log('try ', tries);
}
console.log(results);
}
最后
results
数组包含(除非任务失败10次)所有结果。但仍然
uncaught exceptions
飞来飞去。
then()/catch()
稍后会引起一些时间问题。
任何改进或更好的解决方案,我的问题表示感谢。我的解决方案只允许“波浪式”重试。如果有人能想出一个更好的连续解决方案,我们也将不胜感激。