Promise’s then()

Poby’s Home
2 min readJan 29, 2021

--

How you return from then matters a lot!

Source of the Information

See Mozilla page

Syntax

p.then(onFulfilled[, onRejected]);p.then(value  => { // fulfillment },
reason => { // rejection });

Parameters

onFulfilled: optional

  • A Function called if the Promise is fulfilled.
  • This function has one argument, the fulfillment value.
  • If it is not a function, it is internally replaced with an “identity” function and it returns the received argument.

onRejected: optional

  • A Function called if the Promise is rejected.
  • This function has one argument, the rejection reason.
  • If it is not a function, it is internally replaced with a “Thrower” function and it throws an error it received as an argument.

Return Value

This is very important! Depending on what and how return from fulfillment function, your program's behavior will differ very much!

Once a Promise is fulfilled or rejected, the respective handler function (onFulfilled or onRejected) will be called asynchronously.

The behavior of the handler function follows a specific set of rules. If a handler function:

  1. returns a value: the promise returned by then gets resolved with the returned value as its value.
  2. doesn’t return anything: the promise returned by then gets resolved with a undefined value.
  3. returns an already “fulfilled promise”: the promise returned by then gets fulfilled with that promise’s value as its value.
  4. returns another “pending promise”: the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler (Important!!!!!!). Also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler.
  5. returns an already rejected promise: the promise returned by then gets rejected with that promise’s value as its value.
  6. throws an error: the promise returned by then gets rejected with the thrown error as its value.

Example of returning a “pending promise”

how to create setTimeout promise

function sleep(t: number): Promise<void> {
return new Promise(function (resolve) {
setTimeout(resolve.bind(null), t);
});
}

how to use setTimeout promise

p
.then( () => { return sleep(10);})
.then( () => { doSomething(); // will be executed after 10 ms})

Since sleep() returns a “pending promise”, doSomething() is executed after returned pending promise gets fulfilled.

If you miss return , then doSomething() will not wait until the promise returns by sleep(10) to be fulfilled but will be executed right away.

p
.then( () => { sleep(10);})
.then( () => { doSomething(); // will be executed right away without waiting 10 ms})

--

--

No responses yet