Search code examples
javascriptangularjsasynchronouspromisesimultaneous

Angular fire 2 async calls at once but do not process the second callback until the first finishes


I'm using Angular's $q service to make async requests. I have 2 requests like so (assume I have an angular service named MyService that handles these requests):

MyService.Call1().then(function() {
    //do all the first callback's processing here without waiting for call 2
});

MyService.Call2().then(function() {
    //wait for results of first callback before executing this
});

I have no guarantee that the second call will finish after the first, but I need the results of call 1 in order to do processing in call 2. I understand that I could chain the promises together, meaning that call 2 waits for call 1 to finish before the request is made, but I want to fire both requests at the same time since I have all the data required to do so. What's the best way to do that?

Edit: I can use the results of the first call immediately. They drive some charts on my page. I don't want the first call to wait on the second call to do its processing. I think that rules out mechanisms like $q.all()


Solution

  • An alternative to using $q.all would be to use the first promise in the handler for the second. For example

    var p1 = MyService.Call1().then(function(data) {
        return processedData;
    });
    
    MyService.Call2().then(function(call2Data) {
        return p1.then(function(call1Data) {
            // now you have both sets of data
        });
    });
    

    To address some comments, here's how you could handle errors / promise rejections without having to wait for both promises to resolve or creating multiple catch handlers...

    var p2 = MyService.Call2().then(function(call2Data) {
        return p1.then(function(call1Data) {
            // now you have both sets of data
        });
    });
    
    // use `$q.all` only to handle errors
    $q.all([p1, p2]).catch(function(rejection) {
        // handle the error here
    });