Over a million developers have joined DZone.

Using Promises in Node.js Apps

DZone's Guide to

Using Promises in Node.js Apps

To separate logic of accessing data from the routes, we create separate modules to handle the task of data access.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

To separate logic of accessing data from the routes, we create separate modules to handle the task of data access. When I started learning Node.js, a common pattern that I saw in some samples to separate the data access logic from routing was as follows:

app.get(‘/api/students’, getAllStudents);

//In data access file
exports.getStudents = function(request, response){
  mongoDbObj.students.find().toArray(function(err, data){
      response.send(500,{error: err});

Though this approach separates the logic, we are dealing with request and response inside the data access logic. I am personally not a fan of this approach. But, we cannot return the data or error from the above function as we will get them asynchronously. This is where I started thinking of using promises to refactor the above function.

We have several promise libraries available for Node.js. These days, I am playing with Bluebird. It can be installed using npm.

One of the nice features that bluebird provides is, promisifying existing methods. To turn operations defined by an object into asynchronous, we need to pass the object inside the promisifyAll() method.

var Promise=require('bluebird');
var mongodb=Promise.promisifyAll(require('mongodb')); 

The above snippet creates asynchronous versions of each of the function created inside the object mongodb. Let’s convert some of the snippets from my previous post to use async. Code for establishing a connection to MongoDB changes to:

              console.log("Connected to MongoDB");
                students:  db.collection('students')
            }, function(error){

Let’s fetch details of all students and return the results asynchronously to the caller. On the result of calling find() method, we need to call the asynchronous method toArray() to convert data from documents to array. It makes sense to return a promise in such scenario as we can’t say when the result will be available. Following is the snippet for fetching data that returns a promise:

  return new Promise(function(resolve, reject){
              .toArray(function(err, result){

Finally, the REST API that sends the student data to the browser changes to:

app.get('/api/students, function(request, response){
          }, function(err){
            response.send(500,{error: err});

To me, this seems to be a cleaner approach as the request and response are sent to the model for manipulation. Feel free to express your opinions in the comments.

Happy coding!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

java ,html5 ,javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}