简体   繁体   English

如何使用带有等待的 async.js 库?

[英]How to use async.js libary with an await?

I'm trying to implement the async library so that it polls an API for a transaction until one of them succeeds.我正在尝试实现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;

How ever I can't figure out the correct syntax with the apiMethod 's await function.我怎么无法用apiMethodawait function 找出正确的语法。

I'm getting the error Error: Error: Invalid arguments for async.retry我收到错误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?我该如何实现它,以便每次失败时都会记录所有错误,以及如果在所有 60 次完成之前成功,如何成功退出 60 次重试循环? (if it finishes at for example 14, stop the retries). (如果它在例如 14 处完成,则停止重试)。

You could try the async-retry library.你可以试试async-retry库。

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如我所见, apiMethod应该是未解决的promise,试试这个

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.我无法弄清楚如何使用异步库来执行此操作,但这适用于在我的情况下进行轮询,在这种情况下会抛出错误并在事务尚未处理然后重试时等待一秒钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM