I'm a bit stuck on how I would implement a function to poll a certain HTTP endpoint until I get a certain result (i.e. the endpoint updates), but I would like it to send a request every x seconds and when the first one with the 'correct' response comes back, I'd like to halt/throw away every other process and work with the response that I've gotten.
This means that there can be more than one "in flight" request at any given time and I'm not sure how to implement this, i.e. not wait for a response from a prior request before making another request.
I'm using the request
module which is already async in nature but I'm not sure how i would "fire off" requests every x seconds without waiting on previous ones to complete.
You can use setInterval
. Something like this could work:
function pollIt() {
return new Promise(resolve => {
let done = false;
const interval = setInterval(async () => {
if(done) {
return;
}
const req = await fetch('/test');
if(done) {
return;
}
if(req.status === 200) {// assuming HTTP 200 means "OK", could be something else
done = true;
clearInterval(interval);
resolve(await req.json());
}
}, 1000)
});
}