The states of Promises in Angular :
==> A promise has three states:
- pending: the promise is still in the works
- fulfilled: the promise resolves successfully and returns a value
- rejected: the promise fails with an error
-
* When a promise is fulfilled :
=> When a promise is fulfilled, you can access the resolved data in the
then.
promise .then(value => { return value.anotherPromise() }) .then(another Value => { // use this value })
*When a promise is rejected :
=> When a promise is rejected (that is, the promise fails), you can access the error information returned in the
catch
method of the promise:promise.catch(error => { // interpret error and maybe display something on the UI })
*When a promise is settles :
-
=> Whether the promise is fulfilled or is rejected, the promise has been completed (has been settled).
=> The
finally
method of promises is useful when you want to do something after the promise has settled. This can be cleanup or code you may want to duplicate in thethen
andcatch
methods. -
let dataIsLoading = true; promise .then(data => { // do something with data }) .catch(error => { // do something with error }) .finally(() => { dataIsLoading = false; })