我有下面提到的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?
发布于 2021-05-04 20:42:01
$.ajax返回一个thenable。
将它们收集到一个数组中。将该数组传递给Promise.all。当Promise.all返回的promise解析时,调用fun1。
https://stackoverflow.com/questions/67384934
复制相似问题