Monochromie
Monochromie

Reputation: 449

angularJS - how to perform query one by one?

I have array of objects and want to execute some requests - one for every object.

How to achieve it, since $http-service executes request in async mode?

Like async/await in C#

Upvotes: 1

Views: 74

Answers (2)

AlexStef
AlexStef

Reputation: 90

If you want all the requests to be finished before going on, you could use angular's $q service to generate a promise, and return a result only when every request is done.

// all of this in a controller injecting $q

function fetchAll(objects) {
    var deferred = $q.defer();
    var done = 0;
    var results = {};
    for(var i=0; i < objects.length - 1; i++) {

        // a trick to avoid every iteration to share same i value
        (function(index) {
            $http.get(/* request params here */)
            .then(
                function(data) {
                    results[index] = data;
                    // or results[object.anyProperty] = data;
                    done++;
                    // ensure all calls are successful
                    if (done === objects.length) {
                        deferred.resolve();
                    }
                },
                function() {
                    deferred.reject();
                }
            );
        })(i);

    }

    return deferred.promise;
}

// and call it like this

fetchAll(objects)
.then(function success(result) {
    // continue your business
}, function error(result) {
    // handle error
});

Upvotes: 1

Oreste Viron
Oreste Viron

Reputation: 3805

You can call the next request in the callback of the $http. Something like this :

function sendRequestList(objectList) {

    if (objectList.length > 0) {
        var currentObject = objectList.pop();

        $http.get(/* request params here */)
        .then(
            function() {
                sendRequestList(objectList);
            },
            function() {
                sendRequestList(objectList);
            }
        );
    }
}

However, I don't know a way do achieve this the way you want. Hope this help.

A+

Upvotes: 1

Related Questions