Originally published at https://www.guru99.com
In other tutorials, you would have seen callback functions which are used for Asynchronous events. But sometimes callback functions can become a nightmare when they start becoming nested, and the program starts to become long and complex.
In this tutorial, you will learn
Before we start with promises, let's first revisit what are "callback" functions in Node.js. We have seen these callback functions a lot in the previous chapters, so let's quickly go through one of them.
The example below shows a code snippet, which is used to connect to a MongoDB database and perform an update operation on one of the records in the database.
So what is a promise then? Well, a promise is just an enhancement to callback functions in Node.js. During the development lifecycle, there may be an instance where you would need to nest multiple callback functions together. This can get kind of messy and difficult to maintain at a certain point in time. In short, a promise is an enhancement to callbacks that looks towards alleviating these problems.
The basic syntax of a promise is shown below;
var promise = doSomethingAync() promise.then(onFulfilled, onRejected)
Note: So the key aspect of a promise is the return value. There is no concept of a return value when working with normal callbacks in Node.js. Because of the return value, we have more control of how the callback function can be defined.
In the next topic, we will see an example of promises and how they benefit from callbacks.
Now let's look at an example of how we can use "promises" from within a Node.js application. In order to use promises in a Node.js application, the 'promise' module must first be downloaded and installed.
We will then modify our code as shown below, which updates an Employeename in the 'Employee' collection by using promises.
Step 1) Installing the NPM Modules
To use Promises from within a Node JS application, the promise module is required. To install the promise module, run the below command
npm install promise
Step 2) Modify the code to include promises
var Promise = require('promise'); var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB';MongoClient.connect(url)
.then(function(err, db) {
db.collection(‘Employee’).updateOne({
“EmployeeName”: “Martin”
}, {
$set: {
“EmployeeName”: “Mohan”
}
});
});
Code Explanation:-
Note:
If you now check the contents of your MongoDB database, you will find that if a record with EmployeeName of “Martin” exists, it will be updated to “Mohan.”
To check that the data has been properly inserted in the database, you need to execute the following commands in MongoDB
The first statement ensures that you are connected to the EmployeeDb database. The second statement searches for the record which has the employee name of “Mohan”.
When defining promises, it needs to be noted that the “then” method itself returns a promise. So in a sense, promises can be nested or chained to each other.
In the example below, we use chaining to define 2 callback functions, both of which insert a record into the MongoDB database.
(Note: Chaining is a concept used to link execution of methods to one another. Suppose if your application had 2 methods called ‘methodA’ and ‘methodB.’ And the logic was such that ‘methodB’ should be called after ‘methodA,’ then you would chain the execution in such a way that ‘methodB’ gets called directly after ‘methodA.’)
The key thing to note in this example is that the code becomes cleaner, readable and maintainable by using nested promises.
var Promise = require(‘promise’);
var MongoClient = require(‘mongodb’).MongoClient;
var url = ‘mongodb://localhost/EmployeeDB’;
MongoClient.connect(url).then(function(db) {
db.collection(‘Employee’).insertOne({
Employeeid: 4,
EmployeeName: “NewEmployee”
}).then(function(db1) { db1.collection('Employee').insertOne({ Employeeid: 5, EmployeeName: "NewEmployee1" }) })
});
Code Explanation:-
If you now check the contents of your MongoDB database, you will find the 2 record’s inserted into the MongoDB database.
A custom promise can be created by using a node module called ‘q.’ The ‘q’ library needs to be downloaded and installed using the node package manager. After using the ‘q’ library, the method “denodeify” can be called which will cause any function to become a function which returns a promise.
In the example below, we will create a simple function called “Add” which will add 2 numbers. We will convert this function into a function to return a promise.
Once that is done, we will use the promise returned by the Add function to display a message in the console.log.
Let’s follow the below steps to creating our custom function to return a promise.
Step 1) Installing the NPM Modules
To use ‘q’ from within a Node JS application, the ‘q’ module is required. To install the ‘q’ module, run the below command
npm install q
Step 2) Define the following code which will be used to create the custom promise.
Code Explanation:-
When the above code is run, the output “Addition function completed” will be displayed in the console.log as shown below.
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
Follow us on Facebook | Twitter
☞ Best 50 Nodejs interview questions from Beginners to Advanced in 2019
☞ Node.js 12: The future of server-side JavaScript
☞ An Introduction to Node.js Design Patterns
☞ Getting Started with Promises in Nodejs
☞ Understanding Promises in JavaScript
#node-js #web-development #javascript