when ajax,javascript – 将$.when()/ $.promise()与包含AJAX的函数一起使用

  • Post author:
  • Post category:java


在这个问题上真的很难,而且我知道$.when()可以这样使用(有多个AJAX语句)来保证你完成所有内容.

$.when(

$.ajax({ url: ‘/echo/html/’, success: function(data) {

alert(‘request 1 complete’)

}

}),

$.ajax({ url: ‘/echo/html/’, success: function(data) {

alert(‘request 2 complete’)

}

})

).then( function () { alert(‘all complete’); });

但这只适用于原始的$.ajax(),无论如何都有与函数调用相同的功能,反过来又在它们内部(和其他随机逻辑)中有ajax?

伪代码的想法:

// The functions having the AJAX inside them of course

$.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () {

alert(‘all complete’);

});

解决方法:

当然,让函数返回一个promise对象.

function ajaxFunctionOne() {

return $.ajax(…)

}

function ajaxFunctionTwo() {

var dfd = $.Deferred();

// on some async condition such as dom ready:

$(dfd.resolve);

return dfd.promise();

}

function ajaxFunctionThree() {

// two ajax, one that depends on another

return $.ajax(…).then(function(){

return $.ajax(…);

});

}

$.when(ajaxFunctionOne(),ajaxFunctionTwo(),ajaxFunctionThree()).done(function(){

alert(“all complete”)

});

标签:jquery,javascript,ajax,jquery-deferred

来源: https://codeday.me/bug/20190529/1179777.html