Javascript Promise Lifecycle

Introduction

Each promise goes through a short lifecycle starting in the pending state.

The pending state indicates that the asynchronous operation hasn't completed yet.

A pending promise is considered unsettled.

In the following code, the promise is in the pending state as soon as the readFile() function returns it.


let promise = readFile("example.txt");

Once the asynchronous operation completes, the promise is considered settled.

It will enter one of two possible states:

  • Fulfilled - The promise's asynchronous operation has completed successfully.
  • Rejected - The promise's asynchronous operation didn't complete successfully due to either an error or some other cause.

An internal PromiseState property is set to pending, fulfilled, or rejected to reflect the promise's state.

This property isn't exposed on promise objects, so you can't determine which state the promise is in programmatically.

We can take a specific action when a promise changes state by using the then() method.

The then() method takes two arguments.

Parameter
function


Meaning
call when the promise is fulfilled.
Any additional data related to the asynchronous operation is
passed to this fulfillment function.
function


call when the promise is rejected.
the rejection function is
passed any additional data related to the rejection.



PreviousNext

Related