Skip to content Skip to sidebar Skip to footer

Poll For A Result N Times (with Delays Between Attempts) Before Failing

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 may no

Solution 1:

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

asyncfunctiongetResult() {
  for (let counter = 0; counter < 10; counter += 1) {
    awaitBluebird.delay(1000);
    const res = awaitapiCall();
    if (res.data) {
      return res.data;
    }
  }
  thrownewError('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.

Post a Comment for "Poll For A Result N Times (with Delays Between Attempts) Before Failing"