[英]how to call function on complete execution of inner AJAX?
I have AJAX code as mentioned below:我有 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);
}
});
}); });
In my case what I noticed is fun1 is being called before the complete execution of code inside for loop.在我的情况下,我注意到 fun1 在 for 循环内的代码完全执行之前被调用。 Like if for loop executed ones and the functions gets triggered.
就像如果 for 循环执行了并且函数被触发一样。 Because of this arr contains lesser entries.
因为这个 arr 包含较少的条目。 How can I call function fun1 only after complete execution of loop?
只有在完全执行循环后,我才能调用 function fun1 ?
$.ajax
returns a thenable . $.ajax
返回一个thenable 。
Collect them in an array.将它们收集在一个数组中。 Pass that array to
Promise.all
.将该数组传递给
Promise.all
。 Call fun1
when the promise returned by Promise.all
resolves.当 Promise.all 返回的
Promise.all
解决时调用fun1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.