Javascript: Schedule HTTP requests for later

480 views Asked by At

I'm developing an app using Phonegap (AngularJS + HTML5) and I want some of the functionality to be available even when the user is offline.

What I was thinking of doing is when I need to do an HTTP request, check if the device is online. If it is, then make the request. Otherwise, store the request in an array of other requests, and when you go back online start processing all these requests one-by-one.

So, I have created a service called HttpRequestScheduler which looks something like the following:

.service('HttpRequestSchedule', ['$http', function ($http) {
    var requests = [];

    // schedule function tries to send the request
    // if it doesn't succeed, it adds it to the requests queue
    function schedule(httpRequest) {
        $http(
            httpRequest
        ).success(function () {
        }).error(function () {
            requests.push(httpRequest);
        });
    }

    // this method is called every time the device goes back online
    function processRequests() {
        while (requests.length !== 0) {
            var currentRequest = requests.splice(0, 1)[0];
            $http(
                currentRequest
            ).success(function () {
            }).error(function () {
                requests.push(currentRequest);
            });
        }
    }

    return {
        schedule: schedule,
        processRequests: processRequests
    };

}])

I guess this is a requirement for many apps out there. So my question is, is this the proper/usual way of doing such a thing? Or is there a better way?

1

There are 1 answers

4
Ivan Gabriele On

To check if your device is online or not you should use cordova-plugin-network-information. Also when you're using Angular inside a Cordova-like application, ngCordova will help you a lot !

To answer your question, this a classic problem and the best is to find your own logic mixing an $interval watching regularly the connection via network-information plugin when it's down. When the network connection goes back, you have to execute the list of tasks that you stored in your LocalStorage.