Skip to main content

JavaScript [Q.JS] Are you stuck in nested callback functions?

If you have seen situation when one asynchronous call result used in another asynchronous call. And you tried to make that code look less scary and more readable then you must go through this library and understand it’s nice tricks and syntax.

Just want to give the same example from its site which clearly shows the problem it is trying to solve.

 

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});

 

With QJS library 

 

Q.fcall(step1)
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
    // Do something with value4
}, function (error) {
    // Handle any error from step1 through step4
})
.done();

 

If you want to see its potential uses then you should see one of the WCF data API  breezejs.

To test this library i have created a dummy Ajax function which simulate the Ajax asynchronous behaviour.

 

var Ajax = function(config){
    var emptyFn = function(){},
        xhr = { 
            success : config.success || emptyFn,
            failure: config.failure || emptyFn,
            call: function(id){
                //random response delay
                var randomNum = Math.floor((Math.random()*3000)+1);
                setTimeout(function(){
                    xhr.success('['+config.url+' call]');
                }, randomNum);
            }
        };
    xhr.call();
    return xhr;
}

 

Next step is to wrap Ajax function in QJS promise object. And we are ready to play with QJS features.

 

var ajaxPromise = function(url){
     var deferred = Q.defer(),
        projectMgr = Ajax({
            url: url,
            success: function(res){
                console.log('>>>[success]>>>'+res);
                deferred.resolve(res);
            },
            failure: function(res){
                console.log('>>>[failure]>>>'+res);
                deferred.reject(res);
            } 
        });  
    return deferred.promise;
}

 

Feed all Ajax call response to one function

 

Q.all([
 ajaxPromise('A'),
 ajaxPromise('B'),
 ajaxPromise('C'),
 ajaxPromise('D')])
.spread(function(responseA, responseB, responseC, responseD){
 //handle data
});

 

Waterfall Ajax call where response data passes to the next Ajax call.

 

Q.fcall(ajaxPromise('A'))
.then(ajaxPromise('B'))
.then(ajaxPromise('C'))
.then(ajaxPromise('D'))
.then(function (responseD) {
 // Do something with value4
}, function (error) {
 // Handle any error from step1 through step4
}).done();

 

There are couple more useful functions

fail:   Shorthand function of ‘then’ where you just want to handle the error

fin:   It is a ‘finally’ function which get call without parameter.

Example handler

 

var handlers = {
    mainTask: function(){
            console.debug('main task - ', arguments);
            return 'maintask';
    },
    task1: function(){
            console.debug('then task1 - ', arguments);
            return 'task1';
    },
    task2: function(){
            console.debug('then task2 - ', arguments);
            return 'task2';
    },
    throwError: function(){
            throw new Error('some error');
    },
    handleError: function(){
            console.log('handle error - ', arguments); 
    },
    finallyTask: function(){
            console.debug('then finallyTask - ', arguments);
            return 'finallyTaskDone';    
    }
};

 

Handling the error through ‘then’ function and ‘finally’

 

Q.fcall(handlers.mainTask)
.then(handlers.task1)
.then(handlers.throwError)
.then(handlers.task2, handlers.handleError)
.fin(handlers.finallyTask).done(); 

 

Same behaviour with ‘fail’ shorthand function

 

Q.fcall(handlers.mainTask)
.then(handlers.task1)
.then(handlers.throwError)
.then(handlers.task2)
.fail(handlers.handleError)
.fin(handlers.finallyTask).done(); 

 

There are more stuff you can explore. 

If you are a big fan of one liner code then you can write your code something like below with new array functions

 

var find = function(){ console.log('find'); },
 validate = function() { console.log('validate'); },
 update = function() { console.log('update'); },
 show = function() { console.log('show'); },
 funcs = [find, validate, update, show];

 

With function chaining

 

Q.fcall(find).then(validate).then(update).then(show)

 

Or with new ‘forEach’ function

 

var result = Q.resolve();
funcs.forEach(function(func){
    result = result.then(func);
});

 

Or with ‘reduce’

 

funcs.reduce(function(funca, funcb){
    return funca.then(funcb);
}, Q.resolve())

 

Ok above two were not really one liner but these are pretty compact and expressive.

 

Ajax call retry with some delay

There was a scenario in our project where we wanted to show error message after 5 recursive fail to get the data. And i found much easier to do with this library.

 

function readRetry(url, retryDelay, times){
    return projectMgrPromise(url)
        .then(function(data){
            console.log('got the data.');
        }, function(error){
            if(times == 0){
                throw new Error('Error while reading the data.');
            }
            return Q.delay(retryDelay)
                .then(function(){
                    return readRetry(url, retryDelay, times-1);
                });
        })
        .fail(function(error){
            console.log(error);
        });
}

//function call with 5 retry and 200 delay
readRetry('testUrl', 200, 5);

 

Asynchronous call handing are really hard specially if you are creating single page web application. So it is always better to give some thought on design before writing the code. I still remember battling with async callback issues in our one of the project and we created event system to overcome from it.

 

PS: JQuery and DOJO also support these kind of functions.

 

Some useful links








Comments

Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Recently I found this issue while writing code snippet in "JSFiddle". And after searching, found this was happening because of new feature added in "Chrome 46+". But at the same time Chrome doesn't have support for "allow-modals" property in "sandbox" attribute. Chromium issue for above behavior: https://codereview.chromium.org/1126253007 To make it work you have to add "allow-scripts allow-modals" in "sandbox" attribute, and use "window.alert" instead of "alert". <!-- Sandbox frame will execute javascript and show modal dialogs --> <iframe sandbox="allow-scripts allow-modals" src="iframe.html"> </iframe> Feature added: Block modal dialog inside a sandboxed iframe. Link: https://www.chromestatus.com/feature/4747009953103872 Feature working Demo page: https://googlechrome.github.io/samples/block-modal-dialogs-sandboxed-iframe/index.html

Application Design Notes

Don’t be afraid to write your own code, but be absolutely sure you need to Don't reinvent the wheel Learn more about your libraries and take full advantage  Date time calculation is hard ( leap second ,  leap year ), use trusted library  js-joda ,  momentJs ,  joda (java) Simple is better than perfect (nearly) every time If you can deliver a sub-optimal solution (that solves the problem but has known limitation) in a week instead of a full featured one in a month DO, IT Simple system are Easy to reason about  Easy to debug Easy to refactor Easy to learn Simple doesn't mean you skip good engineering, but you can use duct tape. Build things the right way from the start, refactoring is hard and expensive Security Manage and store passwords securely Telemetry Common retrofitting "grunt work" Internationalization + localization Web Content Accessibility Factoring and styling HTML UI Adding unit test to an existing codebase LOG LOG LOG Log, but do it right We spend lot of t

How to store user password at server!!!

Trick is, you should never store user password… never ever. Now the real question is, then how to authenticate and authorize the user with password. And answer is when user enter the password, we should encrypt the password and store the hints. So next time when user enter the password we follow the same process and compare hints, if both hints are same then password is matched, else it is wrong password. Next question will be, what kind of hints, and how to generate these hints. In simple term hints are the obfuscated and fragmented form of user password. And very important part is hints generation process, which have to be collision resistant , means there will be very less possibility to find the data which generate same hints (like Cryptographic hashing functions ). Below is the simple checklist of password hashing and storing, which you should always keep in mind. PS You're Probably Storing Passwords Incorrectly Storing Passwords - done rig