As we all know In node.js many times we will use asynchronous callback. There are n number of situation where we want to use nested callback where we want to use one callback result to another asynchronous callback. The best way to do that task is use promises . So A promises is an alternative way to approach asynchronous call.
In other word we can say that a promise is a object that represent the result of asynchronous call. This object contain the status (success or failure) of asynchronous call. So lets take an example to explain promises in node.js using q promise library.
Example: Below is the example of promises using node.js.
var FS = require('fs'),
Q = require('q');
Q.nfcall(FS.readFile, "file.txt", "utf-8")
console.log('File has been read:', data);
console.error('Error received:', err);
Here In the example first we will require fs module for file reading and writing and q module for using promises. In q module we have one utility function nfcall() which will convert readFile() to a promises. By this way we will use promises. Before using q module you should install this module using npm . Here is the below command to install npm.
npm install --save q
By this way, we will use promises to manage asynchronous call in node.js.