Javascript Question

How can I add a callback to a function with multiple async calls in JavaScript?

function jsoncall(){
$.getJSON("http://localhost:3000/data", function (data) {...});
$.getJSON("http://localhost:3000/data", function (data) {...});
}

jsoncall.callback(function(){
//do stuff
});


Something like the pseudocode above. Is there a method in JavaScript that considers async calls like the
getJSON
above?

Answer

Use Deferred : https://api.jquery.com/jquery.deferred/

function jsoncall(){
     var $def = $.Deferred();
    $.getJSON("http://localhost:3000/data", function (data) {

      $def.resolve(data);

    });

    return $def;
}
jsoncall.done(function(data){
    //do stuff
});

Or

function jsoncall(fnCallback){

    $.getJSON("http://localhost:3000/data", fnCallback);

}
jsoncall(function(data){
    //do stuff
});
Comments