Mar.29

Promises and Deferred Functions in NodeJS using Q

Introduction
If you come from a mostly synchronous programming language like I have you will run into concepts that may seem hard to grasp or fully understand. This is good news! You’re learning.

Coming from PHP functions can be fairly static, as they were for most of the developmental lifespan of PHP ( until the recent 5.0+ releases ). Moving forward, we must consider functions are variables in themselves. The idea behind promises or deferred functions is the ability to pass functionality, between methods. This differed functionality is at the heart of a promise. A Promise is an ‘eventual result’, which is calculated at a later time. The reason promises work so well in NodeJS is because of its asynchronous nature.

First we need to find a promise library we are comfortable with. Some use bluebird, I like to keep is short and sweet, so I use “q”

npm install q --save

This will give us access to the “Q” module, which gives us simple functions to facilitate promises. You can take any existing function and “promisfy” it so that it can be passed and executed at a later time. In the Q module, this function is called ‘fcall’.

If you prefer the callback methods, then you can create “Deferred methods”, this can be done with Q’s ncall, or defer methods.

If you wish to create a promise function from scratch, then look into Q.promise, as it provides the error, success, and notification objects directly into your promise as such :

var Q = require('q');

function checkName(name) {
    return Q.promise( function(resolve,reject) {
        if (name == 'dan') resolve('You are Dan');
        reject('You are not Dan');
    });
}

checkName('Bob').then( 
    function( success ) {
        console.log("Success : "+success);
    },
    function( error ) {
        console.log("Error : "+error);
    }
}


Why is this important? Because you can now stack steps that facilitate asynchronous functions in a synchronous manner without diving into a nesting tree.

Bad : 


function dothis( function (result) {
    dothat(result,function( resultTwo ) {
        thenThis(resultTwo, function( resultThree ) {
            console.log('Final result : '+resultThree);
        });
    })
});

Better with Q :

dothis().then( function(result) {
    return dothat(result);
}).then ( function(resultTwo) {
    return thenThis(resultTwo);
}).then ( function ( resultThree ) {
    console.log('Final result : ' +resultThree;
});
    
});
NodeJS

Leave a comment