在失败之前轮询结果n次(尝试之间有延迟)

Poll for a result n times (with delays between attempts) before failing

本文关键字:之间 延迟 失败 结果      更新时间:2023-09-26

我们需要编写一个Node.js函数,该函数轮询某个API端点以获得先前请求的计算结果。生成结果需要随机的时间,并且可能根本不会生成结果。我们希望尽快得到它,但我也不想等待太久,这意味着在一定数量的API调用之后,我们希望函数失败(拒绝承诺)。

我们的代码和API之间只有一种通信方式。

const Bluebird = require('bluebird');
function getResult() {
  return new Bluebird(async function (resolve, reject) {
    let counter = 0;
    while (counter < 10) {
      await Bluebird.delay(1000);
      const res = await apiCall();
      if (res.data) {
        resolve(res.data);
      } else {
        counter += 1;
      }
    }
    reject('timeout');
  });
}

这个方法正确吗?

No。这是Promise构造函数反模式的async/await版本!它甚至不会在调用resolve时停止循环,或者在抛出异常时拒绝(例如当resnull时)。
你应该使用

async function getResult() {
  for (let counter = 0; counter < 10; counter += 1) {
    await Bluebird.delay(1000);
    const res = await apiCall();
    if (res.data) {
      return res.data;
    }
  }
  throw new Error('timeout');
}

如果你想确保返回一个Bluebird承诺,而不是一个本地承诺,将其包装在Bluebird.method中或告诉你的转译器使用Bluebird。