如何将async.js库与await一起使用



我正在尝试实现async库,以便它轮询API中的事务,直到其中一个成功为止。

router.get('/', async function (req, res) {
let apiMethod = await service.getTransactionResult(txHash).execute();
async.retry({times: 60, interval: 1000}, apiMethod, function(err, result) {
if(err){
console.log(err);
}else{
return result;
}

});
});
module.exports = router;

我怎么就不能用apiMethodawait函数找出正确的语法。

我收到错误Error: Error: Invalid arguments for async.retry

我该如何实现它,以便每次失败时都会记录所有错误,以及如果在完成所有60之前成功,如何成功退出60重试循环?(如果在例如14结束,则停止重试(。

您可以尝试异步重试库。

await retry(
async (bail) => {
const res = await service.getTransactionResult(txHash).execute();
if (res.status >= 400) {
bail(new Error());
return;
}
const data = await res.text();
return data;
},
{
retries: 60,
}
);

正如我所看到的,apiMethod应该是一个未解决的承诺,试试

router.get('/', async function (req, res) {
let apiMethod = () => (service.getTransactionResult(txHash).execute())
async.retry({times: 60, interval: 1000}, apiMethod, function(err, result) {
if(err){
console.log(err);
}else{
return result;
}

});
});
module.exports = router;
var promises = [];
let request = service.getTransactionResult(txHash);
for(let i = 0; i < 60; i++){
promises.push(request);
}
for(let i = 0; i < 60; i++){
try{
let result = await promises[i].execute();
}catch(err){
console.log(err);
await new Promise(resolve => setTimeout(resolve, 1000));
}

}

我不知道如何使用异步库,但在我的情况下,这适用于轮询,在这种情况下,会抛出错误,并在事务尚未处理时等待一秒钟,然后重试。

最新更新