Wednesday 28 November 2018

Are there better ways of synchronously executing dynamic async functions/promises?

I was hitting an API that had strict rate limiting and therefore wanted to hit the API one request at a time, keeping track of how close I was to hitting the rate limit and pausing execution if necessary. I came up with this solution, but I'm not satisfied with its maintainability/readability/reusability and was wondering if there were other more standard ways of accomplishing the same thing. I've commented the code and removed the error-handling logic for readability. The gist of it is there's an array (queue) that stores async functions waiting to be called. When a client calls the call_api function a new async function is created which wraps the main api call and updates the rate-limiting info after receiving the response from api server. The async function is then added to the queue, where it waits to be executed. Execution happens in a loop that checks the rate-limiting variables first. There is example client code at the bottom. The effect is that the client code doesn't have to know about the rate-limiting - it just awaits the response.https://ift.tt/2PXXltD apologize for the length. I'm not looking for a code review necessarily, just seeing if I'm missing something really obvious about a better way to accomplish this using some idiomatic javascript concept that I'm unfamiliar with.

Submitted November 28, 2018 at 10:13PM by woeeij

No comments:

Post a Comment