Javascript jQuery对Ajax调用的承诺
我想/希望我遗漏了一些关于promise编程范例的东西。我在jQuery上运行以下代码,因为我想从URL\u 1获取数据,然后从URL\u 2获取数据2。其他变量来自围绕这段代码的上下文 然而,我得到的是两次URL的数据Javascript jQuery对Ajax调用的承诺,javascript,jquery,ajax,promise,jquery-1.7,Javascript,Jquery,Ajax,Promise,Jquery 1.7,我想/希望我遗漏了一些关于promise编程范例的东西。我在jQuery上运行以下代码,因为我想从URL\u 1获取数据,然后从URL\u 2获取数据2。其他变量来自围绕这段代码的上下文 然而,我得到的是两次URL的数据 .ajax({ url: URL_1, type: "GET", async: false, cache: false }).then(function (data) { myObj = process(otherObj, data, U
.ajax({
url: URL_1,
type: "GET",
async: false,
cache: false
}).then(function (data) {
myObj = process(otherObj, data, URL_1);
return $.ajax({
url: URL_2,
type: "GET",
async: false,
cache: false
});
}).done(function (data2) {
myObj2 = process_more(data2, URL_2, someObj);
myCounter--;
if (myCounter== 0) {
console.log("%%%% COMPLETE %%%%");
}
});
提前感谢您抽出时间
事实证明,只要jQuery版本大于1.8(我知道但没有注意到我使用的是上一个版本),代码就可以正常工作。我用最新版本替换了jQuery,一切都正常工作。然而@Bergi关于
async:false
无用甚至导致问题的说法是正确的
在jQuery的早期版本中,承诺/延迟模型“被破坏”,并且没有按预期工作/应该与原始承诺模型()一起工作
另请参见:我是这样解决的:
for (var i = 0; i < json.length; i++) {
if(json[i].university_name !== '' && json[i].state_code !== ''){
$.when(
$.ajax({
async: false,
url: "validateUniversityExist.php",
method: 'post',
dataType: 'json',
data:{
'name': json[i].university_name,
'state_code' : json[i].state_code
}
})).then(function( resp, textStatus, jqXHR ) {
if(resp.id_university !== '' || resp.id_university !== undefined){
if (json[i].record_status == 3){
$.ajax({
url: "createNewBenefits.php",
method: 'post',
dataType: 'json',
data:{
'id_university': resp.id_university,
'state_code' : json[i].state_code,
'updated' : json[i].updated,
'id_visa' : json[i].visa_type,
'record_status' : json[i].record_status,
'mandatory' : json[i].mandatory,
'aca' : json[i].aca
}
}); // end insert complete record ajax
}
}
}); // end university when ajax
}
} // end for
for(var i=0;i
使用when和then 不要使用
async:false
。这甚至可能导致承诺出现问题。@Radek-我就是这么想的,我很确定你不能向内的链返回新的承诺。然后,但是测试表明,您实际上可以->因此,只需删除async:false
部分,它就应该可以工作了。您可能是对的,但是async:false
仍然可以工作。我检查了jQuery版本,它是1.8之前的版本,这意味着承诺/延迟模型与原始承诺模型“不一致”。我把jQuery替换为最新版本,现在它工作正常。@ Panais,您可能想考虑蓝鸟的承诺,甚至是本地的承诺,而不是jQuery,在这种事情和错误处理中是有问题的。jQuery的承诺仍然被打破,只是很少看到。