a blog for those who code

Thursday 10 December 2015

How to use Promises in Node.js

In this post we will be discussing about How to use promises in Node.js. In our previous post we have discussed about What is Promise in context of Node.js, in this post we will continue our discussion of using promises in Node.js.

Example : Converting read files in Node.js from Callbacks to Promises.

Simple reading files using callbacks

fs = require('fs');
fs.readFile('file.txt', 'utf8', function(err, data) {
  if(err) {
    return console.log(err);
  }
  console.log(data);
});

After Converting it to Promises

fs = require('fs');
function getSome() {
  return new Promise(function (resolve, reject) {
    fs.readFile('file.txt', 'utf8', function(err, data) {
      if(err) {
        return reject(err)
      }
      return resolve(data)
    })
  })
}

var value = getSome()
             .then(function (data) {
               console.log(data)
             })
             .catch(function(err) {
               console.log(err)
             })

You can even use NPM Package q for denodeifying Node.js callbacks to Promises. According to q, if a function cannot return a value or throw an exception without blocking, it can return promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.

In the figure below it is shown that how you can convert the Callbacks to Simple Promises using Q.

PC : https://www.npmjs.com/package/q

So the above example which we have shown can be rewritten using Q as shown below :

var fs_readfile = Q.denodeify(fs.readFile);
var promise = fs_readfile('file.txt');
promise.then(console.log, console.error);

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment