In this part of the Promises tutorial, we will see the concept of Promises in more detail. This is the second part of the Promises in NodeJS tutorial and if you have not checked out the first part of this tutorial you can visit “Promises in NodeJS part 1”. Now let’s jump right in because we have got a lot to cover and learn in this part.
Dealing with nested promises
In Promises, the “then” method itself returns the promise. We can nest or chain the promises together. Now let’s look at an example.
In this example, we will use chaining to define two callback functions, and the job of these callback functions will be to insert a record in the MongoDB database. For those of you who are not familiar with the concept of chaining, it is a concept that is used to link the execution of two or more methods. If we try to explain this concept through an example, suppose there are two methods called ‘Method1’ and ‘Method2’. And if we want to run the ‘Method2’ right after “Method1” then we would chain the execution in such a way that the second method gets executed right after the second method. The main point here is that the code becomes readable, cleaner, and maintainable by using nested promises.
var Promise = require('promise');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017';
MongoClient.connect(url)
.then(function(client) {
var db = client.db('EmployeeDB');
db.collection('Employee').insertOne({
Employeeid: 4,
EmployeeName: "Waleed"
})
.then(function() {
db.collection('Employee').insertOne({
Employeeid: 5,
EmployeeName: "Obaid"
})
})
});
Code Explanation:-
In this code, you will be able to see two ‘then’ methods that get executed one after another. In the first then clause we are passing the ‘client’ parameter which will return the client we will use this client to make the database connection. After this, we are using collection property to insert new records in the collection ‘Employee’. The insertOne method inserts the record.
We are using the second then clause to insert another record into the database.
On checking your database you will find 2 records inserted in the database.
Output:-
Creating a custom promise
A ‘q’ node module can create a custom promise. The first step is to download the ‘q’ library and then install it using the node package. After using ‘q’ we call “denodeify” method which makes any function return promise. Let’s take a look at an example. We have created a simple “Add” function that adds two numbers. We will convert this “Add” function into a function that returns a promise. In this example, once the function returns a promise, the “Add” function will display a message in the console.log.
Follow the following steps to create your custom promise.
- Step 1:
In the first step, we will install the ‘q’ NPM module to use ‘q’ from within a Node JS application. Run the following command to install the ‘q’ NPM module.
npm install q
The following code will create a custom promise. Type the following code and run it
var Q = require('q');
function Add(){
var a,b,c;
a=5; b=6;
c=a+b;
}
var Display_promise=Q.denodeify(Add);
var promise= Add;
promise.then
{console.log("Addition completed");}
Code Explanation:-
- require(‘q’) includes the ‘q’ library this library helps us to define any function to return a callback.
- In this code after the including the ‘q’ library we created an Add function. This function adds values of two variables and stores them in a third variable ‘c’.
- After the Add function, we have used denodeify method to convert our function into a function that returns a promise. We use ‘q’ library to denodeify our Add function which returns a promise after conversion.
- When we call the “Add” function, we are able to return a promise value.
- We then used ‘then’ keyword to specify that if the function has successfully executed then in the console.log print “Addition function completed”.
Output:-
So this is it for this tutorial. We have covered all the major concepts of promises and how to use them in NodeJS. Promise in NodeJS requires a lot of practice so don’t forget to do a lot of practice. 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. Happy Coding!