I'm writing JavaScript (Node.js) code that calls the Stack Exchange API. One part of the API is that it may return a non-zero value for backoff
, which essentially means "wait n seconds before making another API call like that".
If it matterns, I'm using Axios for my HTTP requests.
A simple function to call the API might look like this:
function getAnswer(id) {
// call the SE API
// return the answer identified by 'id'
}
However, that doesn't handle backoff
. Also, getAnswer(...)
might be called several times in a row, and the first time it gets called, it returns a backoff of ten seconds. Even if that happens, I'd still like the other calls to it to (eventually) return a value (i.e., they wait until it's backed off enough to actually "go").
One way to do this would be some type of queue, where a function iterates through the queue, one call at a time, and checks backoff before waiting. But, that would involve creating an entire new thread for that, and would have to constantly check, so that isn't very efficient.
I've looked at a few libraries - one used requests (which is deprecated), and so caused issues. I don't recall why the other one didn't meet my needs.
We can assume the latest stable release of Node.js, and I don't care about supporting older Node.js versions, so newer features are fair-game, if they make this easier.
Regardless, what's a good way to implement code that can handle backoff in node.js?