AngularJS: Promises usage in angular application

Standard

Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together – increasing readability and making individual functions, within the chain, more reusable.

function getCandidateCareer() {
    ajaxLoader.show();
    careerDetailService.getCountryList()
        .then(function (response) {
            if (response.data)
                $scope.countryList = response.data;
            return careerDetailService.getJobTypeList();
        })
        .then(function (response) {
            if (response.data)
                $scope.jobTypeList = response.data;
            return careerDetailService.getExpertiseLevelList();
        })
        .then(function (response) {
            if (response.data)
                $scope.expertiseLevelList = response.data;
            return careerDetailService.getCandidateCareer();
        })
        .then(function (response) {
            if (response.data) 
                $scope.career = response.data[0];
            ajaxLoader.hide();
        });
};

If you look at code closely, in order to resolve chaining, next async call depends upon completion of previous ajax call, you consume the output as per need of current call and then execute the next async call in queue.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s