如何反复调用异步方法,直到在本机JavaScript中获得成功?
我有一个异步方法,它返回success或fail。我必须一直从另一个方法调用这个异步方法,直到成功。但是如果它重复失败5次,那么我必须停止调用它如何反复调用异步方法,直到在本机JavaScript中获得成功?,javascript,async-await,es6-promise,Javascript,Async Await,Es6 Promise,我有一个异步方法,它返回success或fail。我必须一直从另一个方法调用这个异步方法,直到成功。但是如果它重复失败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) => {
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
}
函数重试(重试次数=5次){
如果(重试次数<0)返回
myAsyncApi(“/url”)
.then(res=>console.log(res))
.catch(res=>重试(重试次数-1))
}
如果您想在调用之间获得一些延迟,可以使用
setTimeout
调用retry通过一点递归,重试应该非常容易。基本上,如果请求成功,只需返回。如果失败,则捕获错误并重试,剩余的尝试次数减少1次
function fetchAndRetry(retryAttempts = 5) {
if (retryAttempts < 0) {
return Promise.reject(new Error("Exceeded maximum retries fetching /url"));
}
console.log("Attempting, " + retryAttempts + " attempts left.");
return myAsyncApi('/url').catch(() => fetchAndRetry(retryAttempts - 1));
}
fetchAndRetry().then(res => console.log(res));
函数fetchAndRetry(retryAttempts=5){
如果(重试次数<0){
return Promise.reject(新错误(“超过了抓取/url的最大重试次数”);
}
log(“正在尝试,+retryAttempts+“尝试离开”);
返回myAsyncApi('/url')。catch(()=>fetchAndRetry(retryAttempts-1));
}
然后(res=>console.log(res));
您可以避免使用async/await,但无法避免工作流是异步的。你最后的评论是什么意思?如果您只是想避免异步/等待,请使用
promise.then()
和promise.catch()
并返回一个承诺。谢谢,这很有帮助
function fetchAndRetry(retryAttempts = 5) {
if (retryAttempts < 0) {
return Promise.reject(new Error("Exceeded maximum retries fetching /url"));
}
console.log("Attempting, " + retryAttempts + " attempts left.");
return myAsyncApi('/url').catch(() => fetchAndRetry(retryAttempts - 1));
}
fetchAndRetry().then(res => console.log(res));