I'm learning to perform a callback after successful results from two functions, one of which is ajax and one is non-ajax (both are asynchronous). In my script there is a non-ajax call to load multiple images at the start of the program, and an ajax (JQuery) call to request a JSON with data for a variable in the script. I've discovered JQuery's when() function for making multiple ajax calls, and I've discovered this answer for making multiple requests before a callback, that might be hackable. I'm chasing my tail a bit on this one and looking for some advice on whether or how to make a function to perform a callback after multiple, mixed functions. Thanks in advance for your thoughts!
Add a comment
|
1 Answer
$.when will actually take in multiple deferred objects, so you can do something like this:
var xhr = ajax();
var images_promise = loadImages();
$.when.apply($, [xhr, images_promise]).done(function () {
// something to do when both are complete
});
Provided that the ajax and loadImages functions return promise objects:
function ajax() {
return $.ajax({
// ajax configuration
});
}
function loadImages() {
// create the deferred promise object
var dfd = new jQuery.Deferred();
$("img").on('load', function() {
// on the load event resolve the promise
dfd.resolve();
});
return dfd;
}
Read more about deferred promises here
8 Comments
gromiczek
Ok, I think I'll need to do some reading on promise objects - I don't yet think there's a promise object in the loadImages function I wrote.
Dan-Nolan
@gromiczek Sounds good. I've added a very simple example of using deferred promises below for reference. Good luck!
gromiczek
So how do I return something (images, or the JSON) from each of these functions after the deferred object has been resolved? Is there a property in the object that holds the returned data? I'm sure this is somewhere in the documentation...
Dan-Nolan
It should be in full detail in the deferred promises link at the bottom of the post. Basically you'll want to pass data through the deferred object's resolve method. Something like
dfd.resolve({name: 'Dan'});. Then in the .done(p1,p2) method, the parameters p1, p2 will be the data you passed through the resolve method and the data returned with the ajax call.guest271314
@gromiczek If possible, post
html, css js ? Perhaps, see also stackoverflow.com/questions/22572795/… ? |