Poll for a result n times (with delays between attempts) before failing
We need to write a Node.js function that will poll a specific API endpoint for the result of a previously requested computation. The result is an arbitrary time that can be generated and may not be generated at all. We would like to get it as soon as possible, but also I don't want to wait too long, which means that after a few API calls, we would like the function to fail (reject the promise).
There is one way to communicate between our code and the 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');
});
}
Is this the correct approach?
source to share
Not. This is the async / await version of the Promise
antipattern constructor ! It doesn't even stop the loop when called, resolve
or rejects when an exception is thrown (like when res
equal null
).
You must 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 Bluebird's promise to be returned and not native, wrap it in, Bluebird.method
or tell your transpiler to use Bluebird.
source to share