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

前端 未结 1 1340
逝去的感伤
逝去的感伤 2020-12-11 13:06

We need to write a Node.js function that polls a certain API endpoint for a result of a previously requested calculation. The result takes a random time to be generated and

相关标签:
1条回答
  • 2020-12-11 13:43

    No. This is the async/await version of the Promise constructor antipattern! It won't even stop the loop when you call resolve, or reject when an exception is thrown (e.g. when res is null).
    You should use

    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');
    }
    

    If you want to ensure that a Bluebird promise is returned, not a native one, wrap it in Bluebird.method or tell your transpiler to use Bluebird.

    0 讨论(0)
提交回复
热议问题