Graham S Graham S - 2 months ago 10
Javascript Question

How to design API that can have either synchronous or asynchronous response

I need my service layer to support making http requests when the app is online, and also saving the requests for later when the app is offline, however this results in the response being either a promise when the app is online, or something synchronous when the app is offline. I currently have

someService.save(data).then(function(response) {
performSomeAction();
});


However the implementation of someService will become

if (isOnline()) {
return http.post()
} else {
cachePostForLater();
}


What is the best thing to return from the service to try and hide the complexity of online / offline saving from the controller layer?

Answer

Your synchronous function should return a promise that you manually resolve. That way, the code that is calling the api service can be agnostic to whether or not the call is made while online or not. If you include $q as a dependency of your service, you can do

function save(){
   if (isOnline()) {
    return http.post()
   } else {
    cachePostForLater();
    return $q.resolve(null);
   }
}
Comments