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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 265
    Comment on it

    Promises are the alternatives of callbacks for delivering the results of asnchronous computations. From the implementation point of view callbacks are easier to implement, promises need some efforts. A promise is used for asynchronous calculations.

    The core idea behind promises promise represents the results of an asynchronous operation.

    A promise have 3 states:

    1: Pending

    This is the initial state of the promise.

    2. Fulfilled

    This represent that the operation is successful.

    3: Rejected

    This represent that the operation is failed.

    Example:

    var Promise = require('promise');
    ar promise = new Promise(function(resolve, reject){
                request("http://www.google.com", function(error, response, body) {
                    console.log("google block...");
                    if (error) { reject(error) }
                    else resolve(body);
                });
    });
    promise
    .then(function(result){
        console.log(result)
    })
    .catch(function(err) {
        console.log("This is error block")
        console.log(err);
    })
    .finally(function() {
        console.log("Final block..");
    })

    You can get the result of both the function at final:-

       

     var asyncFunc1 = function() {
            return "test1"
        };
        var asyncFunc2 = function() {
             return "test2"
        }
        Promise.all([
            asyncFunc1(),
            asyncFunc2(),
        ])
        .then(([result1, result2]) => {
            console.log(result1)
            console.log(result2);
        })
        .catch(err => {
            // Receives first rejection among the Promises
            onsole.log("erro block");
            console.log(result1);
            console.log(result2);
        });
        /*Result:
        result1
        result2
        */

     

 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: