我正在学习从两个功能,其中之一是AJAX,一个非AJAX(都是异步的)成功的结果后进行回调。在我的剧本有一个非Ajax调用在程序开始加载多个图像,和一个Ajax(JQuery的)调用请求数据的JSON在脚本中的变量。我发现jQuery的时()
功能,使多个Ajax调用,我已经发现的这个答案多份请求回调之前,这可能是容易被破解。我追我的尾巴一下就这一个,并寻找有关是否或如何使一个功能多,混合功能后执行回调一些建议。预先感谢您的想法!
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!
$。当实际上将采取多种延期的对象,所以你可以做这样的事情:
$.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
});
前提是 AJAX
和 loadImages
函数返回的承诺对象:
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;
}
了解更多关于推迟承诺这里