I’m trying to write an procedure that does something after 2 objects are returned as a result of the callback of an ajax function.
I know the classic example of using Jquery when():
$.when($.get("http://localhost:3000/url1"),
$.get("http://localhost:3000/url2").done(//do something));
But in my case, I don’t want to trigger the when on the execution of the ajax function, I want the when to trigger from the callback from the execution of the ajax function. Something like:
$.get("http://localhost:3000/url1", function(data){
function(){
//do something with the data, and return myobj1;
}
});
$.get("http://localhost:3000/url2", function(data){
function(){
//do something with the data, and return myobj2;
}
});
$.when(obj1, obj2).done(function(){
//do something with these 2 objects
});
But of course, that doesn’t work. Ideas?
That actually should work.
jQuery.when()takes multiple arguments and fires once they all have completed returning each results arguments as an array:If you don’t want to handle the requests together you can create your own deferreds and use those: