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.
What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.
Simply put you can use $q. defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.
then() function to handle the callbacks. Traditional promises (using the $q Service in Angular) have a . then() function to provide a continuation on success or failure, and . then() receives parameters for a success and failure callback.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With