Saturday, August 18, 2018

Building an indeterminate array of functions to pass to $q.all

I'm building an array of functions to pass to $q.all, and I'm wondering if I'm doing it correctly, or if each function will execute separately as I push it into the array.

My code looks like this:

function setParallelRequests() {
    var promiseArray = [];
    var counter;

    for (counter; counter < factory.cards.length; counter++) {

        var data = {
            reference: factory.cards[counter].reference
        };

        promiseArray.push(fetchState(data));
    }

    return $q.all(promiseArray)
        .then(function(response){

            return factory.cards;

        }).catch(function(error){
            return $q.reject(error);
        });
}

function fetchState(data) {

    return $http.post('/returnState', data)
       .then(function(response) {

            alert("got the state!");

        })
        .catch(function(error){

            return $q.reject(error);
         });

}

Will the code execute as I'm pushing it in the array or will it only execute when $q.all runs?

If it isn't done correctly, what would be the best way to do it?

No comments:

Post a Comment