Callback after multiple ajax and non-ajax function

2019-07-31 09:11发布

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!

1条回答
男人必须洒脱
2楼-- · 2019-07-31 09:55

$.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

查看更多
登录 后发表回答