javascript - 如何重复调用异步方法,直到在原生 JavaScript 中获得成功?
问题描述
我有一个返回成功或失败的异步方法。我必须继续从另一个方法调用这个异步方法,直到我成功。但如果它反复失败 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
如果你想在通话之间有一些延迟,你可以打电话给 retry
推荐阅读
- mapbox - 我如何在片段中成功实现 android mapbox android sdk
- javascript - 如何将属性插入嵌套数组的叶节点?
- ruby-on-rails - 在红宝石救援后继续脚本
- css - 从左右两侧裁剪 SVG
- sql - 将字符串拆分为列中的单词
- go - 如何在中间件 go-chi 中获取路由
- firebreath - 如何在插件层中创建一个窗口,在 onWindowAttached 中启动一个线程,何时调用
- css - 在 Salesforce 中升级到 Font Awesome 5
- php - 在 PHP 中以区域语言返回 JSON 数据
- java - 排序算法中的截止值是什么?