Quantcast
Viewing all articles
Browse latest Browse all 42

Promise in JavaScript / Node.js–Part1

As we have discussed earlier callbacks are the basic building blocks of asynchronous programming in JavaScript/Node.js , they are used for notifying when an asynchronous operation is completed. But callbacks when used directly comes with a set of problems like Callback Hell and complex and less-maintainable code required to implement the asynchronous control flows from scratch ( obviously a library like async can be of help here).

Promise(s) are considered to be the next step of improvement on top of bare continuation passing style (CPS) callbacks. Promise is an object that contains the status of an asynchronous operation and eventually the result ( success / failure). A Promise object has three states:

  • Pending – When the asynchronous operation is in-progress.
  • Fulfilled – When the asynchronous operation is successfully completed.
  • Rejected – When the asynchronous operation is terminated with an error.

We need to use Promise.then method to receive and use the result of fulfilment or, error. The Promise.then method comes with the following signature Promise.then(onFulfilled, onRejected).

The Promise constructor creates a new Promise object accepting two function objects as input:

new Promise(( resolve, reject ) => {….})

  • resolve (obj) – This function is invoked when the Promise is fulfilled.
  • reject (obj) – This function is invoked when the Promise is terminated with an error.

We will start exploring Promise with it’s constructor and the “then” function. But first let’s start with an example with callback and then we will develop a Promise based version of the same.

Image may be NSFW.
Clik here to view.
image

The code below shows the Promise based version of the greater than (gt) function. Here, the gtPromise function returns a new Promise object and the resolve callback is invoked in case of successful execution and reject callback is executed in case of an error.

Image may be NSFW.
Clik here to view.
image

Now we need consume i.e. execute or use this Promise by passing the resolve and reject callbacks using the then function.

Image may be NSFW.
Clik here to view.
image

We can refine the above code by using the Promise.catch(onRejected) which is nothing but a syntactic sugar coat on Promise.then (null, onRejected).

Image may be NSFW.
Clik here to view.
image

In the above example we transformed a callback based function by returning a Promise object. This process is known as promisification.

In the next post we will take a look into how promises can be chained together.


    Viewing all articles
    Browse latest Browse all 42

    Trending Articles