错误处理:How can I wait and re execute function after a timeout.



我想通过等待执行和重新执行函数来处理异步超时,包括失败后的错误处理。

伪代码:

01 call and await async function update()
02 if no error -> continue to line 05
03 sleep for 10000ms
04 Jump to line 01 //call update() again and handle possible errors
05 //continues execution

看起来很简单,但是我不能让异步部分工作

一些通用结构没有任何承诺处理


let success = false;
while (!success) {
try{
update()
success = true;
} catch (e) {
setTimeout(() => {},10000)
}
}

我知道我应该处理.catch和承诺,但不能找出。

感谢您的帮助和解释

不确定这是否是您正在寻找的,但这里有一个重试异步调用直到成功的示例,每次尝试之间有3秒延迟:

const wait = timeout => new Promise(resolve => setTimeout(resolve, timeout));
let counter = 0;
async function update() {
console.log('Updating...');
await wait(1000)
if (counter === 3) {
console.log('Update success');
} else {
counter += 1;
throw new Error('Update failure');
}
}
async function callUpdateUntilSuccess() {
try {
await update();
}catch(err) {
console.error(err);
await wait(3000);
return callUpdateUntilSuccess();
}
}
(async () => {
await callUpdateUntilSuccess();
})();

相关内容

最新更新