States of the Angular Promise

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 the then and catch methods.

  • let dataIsLoading = true;
    
    promise
      .then(data => {
        // do something with data
      })
      .catch(error => {
       // do something with error
      })
      .finally(() => {
        dataIsLoading = false;
      })

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories