Skip to content Skip to sidebar Skip to footer

Angularjs : Chaining Promises

Following the suggestions from AngularJS validation and promises, I would like to chain confirmation dialogs and thus validate several steps at once. Based on data provided by the

Solution 1:

dfsq started writing an answer but deleted his so with his blessing I'm adding my take on it:

confirmSteps = function() {
    return fetchSomeData()
        .then(confirmStep1(data))
        .then(confirmStep2(data))
        .then(confirmStep3(data));
}

This calls functions, it's the same as setTimeout(alert("Hi"),5) you don't want to be calling the functions you want to chain them. Like setTimeout(function(){ alert("Hi"); }, 5);

confirmSteps = function() {
    returnfetchSomeData()
        .then(confirmStep1)
        .then(confirmStep2)
        .then(confirmStep3);
}

However, that would pass data to the first promise only and the result of the previous promise to the next one, instead you want to pass data to all three, you can do this by neting one level:

confirmSteps = function() {
    returnfetchSomeData().then(function(data){
        var v1, v2;
        returnconfirmStep1(data).then(function(d){ 
           v1 = d;
           returnconfirmStep2(data);
        }).then(function(d){
           v2 = d;
           returnconfirmStep3(data);
        }).then(function(v3){
            return v1 && v2 && v3;
        })
    });
};

This works but it's kind of crufty, instead you can use short circuiting - kind of like how && only evaluates the left hand side if it's falsey. Moreover we can do all error handling in a central location. This would make your code look like.

confirmStep1 = function(data) {
    if (data.condition1) return $q.when(true);
    return confirmDialogService.popConfirm('step1');
};

confirmStep2 = function(data) {
    if (data.condition2) return $q.when(true);
    return confirmDialogService.popConfirm('step2');
};

confirmStep3 = function(data) {
    if (data.condition3) return $q.when(true);
    return confirmDialogService.popConfirm('step3'):
};

confirmSteps = function() {
    vardata = fetchSomeData();
    returndata.then(confirmStep1).then(function(soFar){ 
         if(!soFar) returnfalse; 
         returndata.then(confirmStep2); 
    }).then(function(soFar){ 
         if(!soFar) returnfalse; 
         returndata.then(confirmStep3); 
    }).catch(function(){ returnfalse; });
};

As an extra tip this:

fetchSomeData = function() {
    var deferred = $q.defer();
    api.fetchData(param1, param2, param3)
        .then(function(data) {
        deferred.resolve(data.content);
    }, api.errorHandler);
    return deferred.promise;
};

Can simply become:

fetchSomeData = function() {
    return api.fetchData(param1, param2, param3).then(function(data) {
        return data.content;
    }, api.errorHandler);
};

Post a Comment for "Angularjs : Chaining Promises"