JS Promise

Short notes on Javascript Promise, .then(), and .catch()

What is Promise? Promise is an object that may produce a single value (could be either a resolve value or an reject value in the future. ( Medium - Eric Elliott)

A promise could be chained with .then() and .catch(). The following cases describes the control flow on a Promise chain. .then() accepts two callback functions - onResolve() and onReject(). When an error occurs, onReject() is executed. The image below nicely describes this.


Figure 1. Rejection is handled on .then().

WAcpP.png (Image from Stackoverflow)


However, the said approach of handling the error/ rejection on .then() is said to be an anti-pattern. When an error occurrs on the onResolve() callback, onReject() won't be able to handle it. Instead, the recommended/general approach in handling rejections or errors is thru the use of .catch(). The downside to this is it is fairly hard to identify on which part of the Promise chain the error occured. A solution to this is explicitely put an identifier to reject calls. e.g. reject(['Function 1', err]) The image below shows the control flow in such case.


Figure 2. Rejection is handled on .catch().

wX5mr.png (Image from StackOverflow)


The following are some code snippets on the usage of promise chains.

//logs ["catch", "reject value"]
const promise = () => new Promise((resolve, reject) => {
reject('reject value')
}).then(
    res=>[res,1]
  ).then(
  res=>console.log(res,2)
  ).catch(err=>
  console.log('catch', err))

promise();
//logs [["resolve value", 1], 2]
const promise = () => new Promise((resolve, reject) => {
resolve('resolve value');
}).then(
    res=>[res,1]
  ).then(
  res=>console.log(res,2)
  ).catch(err=>
  console.log('catch', err))

promise();
//logs ["reject value", 1]
//     [undefined, 2]
const promise = () => new Promise((resolve, reject) => {
reject('reject value')
}).then(
    res=>[res,1],
    err=>console.log(err, 1)
  ).then(
  res=>console.log(res,2)
  ).catch(err=>
  console.log('catch', err))

promise();

Ref: medium.com/javascript-scene/master-the-java..

No Comments Yet