【问题标题】:Async call in while loop with time interval in NodejsNodejs中带有时间间隔的while循环中的异步调用
【发布时间】:2022-08-08 23:48:35
【问题描述】:

我正在尝试实现一个重试过程,该过程应该进行异步调用,并提供 N 次的时间间隔。这是示例代码。

async function client(){
  const options = {
    method: \'GET\',
    headers: {
      \'content-type\': \'application/json\'
    }
  }
  const resp = await axios(\'url://someurl.com\', options);
  return resp; // returns { processingFinished: true or false}
}


export async function service() {
  let processed = false;
  let retry = 0;
  while (!processed && retry < 10) {
    // eslint-disable-next-line no-await-in-loop
    const { processingFinished } = await client();
    processed = processingFinished;
    retry++;
  }
  return processed;
}

async function controller(req, res, next){
  try{
    const value = await service();
    res.send(value);
    next();
  } catch(err){
    next(err);
  }
}

在重试之前,我希望每次通话之间有 500 毫秒的间隔。请帮忙。

标签: node.js while-loop async-await


【解决方案1】:

您的代码似乎没问题,您可以使用这样的辅助函数添加延迟:

const wait = (ms) => new Promise(r => setTimeout(r, ms));

在重试循环中使用它:

 while (!processed && retry < 10) {
    // eslint-disable-next-line no-await-in-loop
    const { processingFinished } = await client();
    processed = processingFinished;
    if (!processed) await wait(500); // add this
    retry++;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多