gpt4 book ai didi

javascript - 如何在原生 JavaScript 中重复调用异步方法直到获得成功?

转载 作者:行者123 更新时间:2023-11-30 11:02:29 28 4
gpt4 key购买 nike

我有一个返回成功或失败的异步方法。我必须继续从另一个方法调用这个异步方法,直到我成功为止。但是,如果它反复失败 5 次,那么我必须停止调用它。

let count = 0;

function myAsyncApi(url){

//this is a fake async method which return success at certain point of time

return new Promise((resolve, reject) => {
if(count === 5){
setTimeout(function(){
resolve('succes')
}, 100);
}
else{
setTimeout(function(){
reject('failure');
}, 100);
}

count++;
});
}

function retry(){
// I have to call myAsyncApi('/url') from this function repeatedly
// Whenever we get success from myAsyncApi(url) we have to stop calling the API
// if we get fail then call myAsyncApi('/url') again until count reaches 5

// how can we achieve this without using async/await in this function


}

最佳答案

function retry(retries = 5) {
if (retries < 0) return
myAsyncApi('/url')
.then(res => console.log(res))
.catch(res => retry(retries - 1))
}

如果你想在调用之间有一些延迟,你可以使用 setTimeout 调用重试

关于javascript - 如何在原生 JavaScript 中重复调用异步方法直到获得成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098954/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com