This post is going to be about writing promises in nodejs. In many projects that utilize a database server, it’s common that the application needs to wait for the data to be fetched before performing any operations on it. Therefore we need to implement an asynchronous function using promises.

Technologies

  • Node – v6.11.5

Usage

Promise is a built in library in nodejs. It contains two parameters: resolve, reject. Resolve and reject can be named something else but the first parameter represents resolve and second is reject. Promise is always in one of these state: pending,  fulfilled and rejected. Before completing the operation, the promise will always be in the pending state, and you can set its state to either fulfilled or rejected by using the resolve and reject callbacks.

An example of promise may look like this:

var testFunction = () => {
  return new Promise(function(resolve, reject) {
    // Some database operations here
    if (value) {
      resolve(value);
    } else {
      reject(value);
    }
  });
};

When using this function, you can use .then to use the results of the promise. Here is an example:

testFunction()
  .then(function(result) {
    // Do something with the result data
  }, function(error){
    // Handle error
  });

The result field will have the value returned from resolve(value) and error will have the value returned from reject(value). I have seen a lot of developers either forget or purposefully leave out the error handling part of the promise, but I would recommend to leave it in there, especially if it is used for REST APIs, so you can send res.status(500).send() there.

For people who are still confused about promises, a real life example would be: you are at a fast food place, you are placing your order but you left your wallet in your car. So you made a promise with the cashier that you will go get your wallet from your car and pay when you come back. So the cashier continues to send the order to prepare your food, and when you come back you paid the cashier what you owed. From this example, notice that by making the promise, the cashier was able to continue the process by sending in your order and not block any other processes from operating.

Leave a Reply

Your email address will not be published. Required fields are marked *