Question

I have a synchronous API to invoke a server (HTTP GET) currently implemented with XMLHttpRequest.

The API does caching and will, if cache isn't deemed too old, return from the cache and invoke the server asynchronous to refresh cache.

Sometimes cache isn't available or too old, and then the API will synchronous call the server to fetch an accurate value before returning result to caller.

Result will contain a boolean success flag along with payload and clients handles result accordingly by looking at this flag.

There are two problems I can see with doing like this; When cache isn't available and server isn't reachable or answering slow I would like to bring up a spinner so that the user is aware we are waiting for server. In addition I would like to set a timeout value where we abort server request and handle the error accordingly.

Seems like I should be able to use setTimout operations but I have not been successful. Preferably I would like to keep clients intact (not change the API to asynchronous).

Is there a way to achieve this?

Was it helpful?

Solution

The synchronous API was made responsive by maintaining a cache that was pulled from server asynchronous. The cache was protected by a grace period under which we do not pull new value from server to avoid hammering the server.

For the most cases this was enough to assert there was always a cached value that could be provided to the client.

For a few cases where we have to pull new data the best solution would be to go fully asynchronous, that is also update client code.

Currently that is not an option, so in addition to above a heartbeat mechanism was put in place that toggles online/offline status to prevent trying synchronous pulls when offline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top