I'm trying to implement the async library so that it polls an API for a transaction until one of them succeeds.
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;
How ever I can't figure out the correct syntax with the apiMethod's await function.
I'm getting the error Error: Error: Invalid arguments for async.retry
How do I implement it so the errors are all logged everytime it fails and also how to successfully exit the 60 retry loop if it succeeds before all 60 are finished? (if it finishes at for example 14, stop the retries).
You could try the async-retry library.
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,
}
);
As I can see it, apiMethod is supposed to be an unresolved promise, try this out
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));
}
}
I couldn't figure out how to do it with the async library but this worked for polling in my situation where the error would be thrown and waits a second when the transaction hasn't been processed yet and then retried.