Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Node.js Promises

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 279
    Comment on it

    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.

    // readFileUsingPromises.js
    var FS = require('fs'),
        Q = require('q');
    
    Q.nfcall(FS.readFile, "file.txt", "utf-8")
    .then(function(data) {      
        console.log('File has been read:', data);
    })
    .fail(function(err) {
        console.error('Error received:', err);
    })
    .done();

     

    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.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: