nshew13
nshew13

Reputation: 3097

want multiple, independent requests resolved concurrently before a final, dependent action (AngularJS)

Promises are one of those things that I can understand while I'm looking at them, but then the comprehension vanishes when I look away.

I need to grab two pieces of data asynchronously, then combine the result and store it in a cookie. I think I could implement a vanilla promise chain without much difficulty. That is,

loadData1().then(loadData2).then(setCookie);

However, I don't need to wait for one request to finish before making the other. How can I do something like

(loadData1(); loadData2();).then(setCookie);

Upvotes: 0

Views: 80

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Here's a quick example using $q.all:

$q.all([
    (function () {
        var d = $q.defer();
        API.get({}, function (data) {
            d.resolve(data);
        });
        return d.promise;
    })(),
    (function () {
        var d = $q.defer();
        API.getMore({}, function (data) {
            d.resolve(data);
        });
        return d.promise;
    })()
]).then(function(responses) {
    //responses contains an array of all your data responses, in the order they were chained to $q
});

Upvotes: 1

Related Questions