Skip to main content

Node.js Promises

·417 words·2 mins
Table of Contents
Node.js - This article is part of a series.
Part : This Article

We look at the construct of Promises in JavaScript. Promises in JavaScript are an object that will return a value in the future. It’s a proxy from something whose value is not known at the time of creation. It’s used for asynchronous programming in JavaScript.

Promise in JavaScript has 3 states,

  • Pending - initial state
  • Fulfilled - operation completed successfully
  • Rejected - operation failed

It was a lot easier to understand Promises with the help of an analogy. Let’s say, you ask your friend to drop you at the airport tomorrow and he assures you that he will do so. This is a promise in a pending state. Let’s consider the 2 scenarios that might play out. He drops you tomorrow at the airport; then the promise is fulfilled. But, if he fails to do so, then the promise is rejected. You have to handle the situation yourself, let’s say by taking a cab.

goToAirport()
.then('Go with a friend') //Friend comes to pick you up
.catch('Go in a cab'); //Friend is not able to make it

So, in JavaScript Promises, we either resolve the promise or reject the promise.

Create a new Promise
#

To create a new Promise, we can use the consturctor as follows. It takes 2 arguments, resolve and reject(both are basically callbacks).

const promise = new Promise((resolve, reject) => {
  /* Do something here */
})

We can execute a Promise as follows,

promise.then(
    //do something
)
.catch(
    //do something
);

So, let’s try writing a promise for the analogy we took above.

const goToAirport = () => {
  return new Promise((resolve, reject) => {
    setTimeout(()=> {
      if ('Friend comes to pick you up'
 === 'Friend comes to pick you up') {
        resolve('Go with a friend')
      } else {
        reject('Go in a cab')
      }
    }, 1000)
  })
};

const promise1 = goToAirport();
console.log(promise);

const promise2 = goToAirport()
  .then(resp => console.log(resp))
  .catch(err => console.log(err));

If we call the function directly and try to log the promise, we will see that the promise is in pending status. Feel free to change the time to 10000ms if required.

But the second promise execution, will result in the expected result Go with a friend. We can change the if condition to fail to see the reject scenario.

One of the major advantages of writing code like this rather than using callbacks is that it’s easier to read and handle errors.

We will look in detail about async-await in a future post plus compare callbacks, promises, and async-await.

Node.js - This article is part of a series.
Part : This Article