Promises in NodeJS tutorial (part 1)

In this Promises in NodeJS tutorial and we will be discussing promises in detail from introduction to implementing promises. This tutorial is in two parts and this is the first part of Promises in NodeJS. So let’s jump right into this tutorial.

What are promises?

Before starting with promises, let’s revise ‘callback” functions in NodeJS. We have already discussed callbacks in detail in previous tutorials, so we will just slightly touch the concept of callbacks again and we will also see how to use them with promises.  

The first step is to connect to MongoDB. We have done this part before in many tutorials but we will do it again once more for you in case you have forgotten. You will need to type in the following code to connect the client to the database. 

MongoClient.connect('mongodb://localhost:27017', function (err, client) {
  if (err) throw err;
 
  var db = client.db('EmployeeDB');
 
    db.collection('Employee').insertOne({
        Employeeid: 4,
        EmployeeName: "NewEmployee"
    });
 
});

MongoClient will connect you to the database and you can check it by going to your MongoDB compass. You will find that this code has inserted some data into it. You should be able to see the following data in your MongoDB compass.

Code Explanation:-

  • function(err,client) is the declaration of anonymous or callback function. When the client creates connection to MongoDb, it returns to callback function. This all connection operation takes place in the background and when it all completes it calls the callback function. One keypoint of NodeJS is it allows many operations to take place concurrently. None of the user is stopped from performing an operation. 
  • The part inside the function(err, client) executes once client actually calls the callback function. This callback function is responsible for updating one record of MongoDB database. 

Output:

If we talk about promises, they are just an enhancement of callback functions in NodeJS. In development, there are many occasions where callback functions are nested together which makes the code very messy and difficult to maintain. Promises solve these problems. The basic syntax is given in the code below.

 var Promise = require('promise');
 var MongoClient = require('mongodb').MongoClient;
  • In the first line we have “async()” which is just any callback function and does some sort of processing. 
  • When async() gets called a value called “promise” will be returned. On returning, promise can have two possible outputs. One output is success which comes from ‘onFulfilled’ parameter and other one is failed which comes from ‘onRejected’ parameter. These outputs are defined by ‘then clause’.  

The key concept that a promise has is the key value. Normal callback functions has no concept of return values. With the return values, we have more power over defining callbacks i.e how we want to define those callback functions.  

In the next topic, we will see an example of promises and how they benefit from callbacks.

Callbacks to promises

In this topic, we will be looking at an example of promises and will see how promises benefit from callbacks. For this example, you will need to follow the following steps.

  • Step 1: To use promises we need promise module. Promise module should be downloaded and install. The promise module can be installed using npm install promise command.   
  • Step 2: We will modify the code we used above for this example. Make the following changes in the code given in the previous example.
var MongoClient = require('mongodb').MongoClient;
var Promise = require('promise');
MongoClient.connect('mongodb://localhost:27017').then(function(client){


  var db = client.db('EmployeeDB');

    db.collection('Employee').insertOne({
        Employeeid: 4,
        EmployeeName: "NewEmployee"
    });

}); 

Code Explanation:-

  1. The first line adds the promise module which helps us include the promise functionality in our application.
  2.  .then(function(client) Helps us execute the code inside the function once the database connection is established. 
  3. Inside the callback method the insertOne adds new record to the database.

Output:

So this is it for the first part of Promises in NodeJS and we really hope you found it easy to understand and implement. You can read more on promises by visiting MDN Web Docs website where you will find the in-depth documentation of Promises and many other concepts in NodeJS. In the next tutorial, we will see promises in more depth and will learn more about promises. You must practice the concepts of this tutorial before moving next.

Scroll to Top