我有如下所述的AJAX代码:
$("#id").click(function(e){
e.preventDefault();
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
param: id
},
datatype: 'json',
success: function(p){
let arr = [];
const obj = JSON.parse(p);
if (obj.RETVAL == true) {
var i;
for(i=0; i< 6 ; i++){
$.ajax({
url: 'url2',
type: 'post',
data: {
method: 'method2',
param: id2
},
success: function(r){
if (r>1) {
}
else{
arr.push(r); //this array will be passed in fun1
}
}
});
}
}
fun1(arr);
}
});
});
在我的例子中,我注意到fun1是在for循环内的代码完全执行之前被调用的。就像if for循环执行的一样,函数会被触发。因此,arr包含较少的条目。如何只有在循环执行完毕后才能调用函数fun1?
$.ajax
返回一个值。
将它们收集成阵列。将该数组传递给Promise.all
。当Promise.all
返回的promise解析时,调用fun1
。