Angular - Is .finally() Called At the End of Every Path in a Chained Promise Decision Tree?

Lloyd Banks picture Lloyd Banks · May 6, 2016 · Viewed 12.4k times · Source

I have the following chained sequence of promises:

$scope.promisesInProgress = true
myService.myFirstPromise(id)
    .then(function(data){
        $scope.firstResponse = data;
        return myService.mySecondPromise(id);
    })
    .then(function(data){
        $scope.secondResponse = data;
    })
    .finally(function(){
        $scope.promisesInProgress = false;
    });

Is the finally() callback function being called at the very end no matter what the success / failure of the previous two promises are?

For example, if myFirstPromise() returned a 400 response, mySecondPromise() will never be called - but I assume the finally() block would still be thrown? The same should be true if mySecondPromise() returns a 400 (and $scope.secondResponse is never set) and if both promises return 200s.

Answer

MarkoCen picture MarkoCen · May 6, 2016

Angular 1.x $q service inspired by Kris Kowal's Q, based on docs:

finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

so yes, no matter myFirstPromise resolved or rejected, the finally() block would always be called

UPDATED,

to be noticed, the finally() block of myFirstPromise would be called before mySecondPromise resolved(or rejected), because myFirstPromise and mySecondPromise are different promise instance, and mySecondPromise promise instance created after myFirstPromise resolved