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

在这个问题上真的很难,而且我知道$.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值