如何解决我可以让 async.retry 方法重试,即使查询成功,但基于条件
我正在研究 node.js 模块 async,我想知道是否有办法将 async.retry 方法更改为即使操作成功也可以重试,但根据某些条件或响应停止,假设它是一个 api打电话。
根据它的 docs ,该函数将继续尝试失败时的任务,直到成功。如果成功,它只会运行那一次但是我怎样才能让它在成功的操作上也能正常工作并使其成功在某些情况下停止?
const async = require('async');
const axios = require('axios');
const api = async () => {
const uri = 'https://jsonplaceholder.typicode.com/todos/1';
try {
const results = await axios.get(uri);
return results.data;
} catch (error) {
throw error;
}
};
const retryPolicy = async (apiMethod) => {
async.retry({ times: 3,interval: 200 },apiMethod,function (err,result) {
// should retry untill the condition is met
if (result.data.userId == 5) {
// stop retring
}
});
};
retryPolicy(api);
解决方法
我认为这是不可能的。 在 async.retry documentation 上,您可以找到以下说明:
尝试从任务中获得成功响应的次数不超过多次 在返回错误之前的次数。如果任务成功, 回调将传递成功任务的结果。我摔倒 尝试失败,回调将传递错误和结果(如果 任何)最后的尝试。
然而,使用给定 here 的延迟函数,你可以用另一种方式做你想做的事:
const async = require('async');
const axios = require('axios');
const delay = (t,val) => {
return new Promise((resolve) => {
setTimeout(() => { resolve(val) },t);
});
}
const api = async () => {
const uri = 'https://jsonplaceholder.typicode.com/todos/1';
try {
const results = await axios.get(uri);
return results.data;
} catch (error) {
throw error;
}
};
const retryPolicy = async (apiMethod) => {
const times = 3
const interval = 200
let data
for (count = 0; count < 3; count++) {
try {
data = await apiMethod()
catch(e) {
console.log(e)
await delay(interval)
continue
}
if (data.userId === 5) {
break;
}
await delay(interval)
}
// do something
};
retryPolicy(api);
,
是的,如果不满足条件,您可以抛出自定义错误。应该是这样的:
const async = require('async');
const axios = require('axios');
const api = async () => {
const uri = 'https://jsonplaceholder.typicode.com/todos/1';
try {
const results = await axios.get(uri);
if(typeof result.data.userId != 'undefined' && result.data.userId == 5){ // change this condition to fit your needs
return results.data;
}else{
throw {name : "BadDataError",message : "I don't like the data I got"};
}
} catch (error) {
throw error;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。