Search code examples
angularjsasynchronouspromiseangular-promisedeferred

Asynchronous call defer and promise chain


I stuck with ashync call chain. I tried google but couldn't found exact answer.

requirement is I have a method

callApi(){
     I am calling 4 service that all are asynchronous.
     I want to chain all the asynchronous calls so that I can do  
     defer.resolve only when all request are done 
}

Any help would be great help. Thanks in Advance.


Solution

  • You can just use $q.all(). It takes an array of promises and returns a promise, that will resolve when all promises in that array have resolved.

    Example:

    function callMultipleServices() {
        return $q.all([
            //Just some random functions returning promises...
            someAsyncService(),
            $http.get('http://google.de'),
            someOtherAsyncService()
        ]) //.then(function(resultArray) { return doSomethingWith(resultArray) }) 
    }
    

    The returned promise will resolve with an array, containing the resolved values of the promises you passed in. If you want your promise to return a single value that is somehow derived from the service results, just add a .then that takes the results and somehow calculates your final promise result (as in the comment above)