我有两个函数,其中有ajax调用
。
function a(){
ajaxCall_A();
}
function b(){
ajaxCall_B();
}
我还有另一个函数,它按 a
然后 b
的顺序调用这两个函数。
function c(){
a();
b();
// expectation : function 'b' will get executed only after function 'a' finished it's execution
}
我不确定它们是否按我的预期工作。有时可以,但有时不行。我认为这是因为 ajax 调用是异步的,在它们内部。
如何运行函数“c”中的两个函数来达到预期目的。
注意:函数如下
function a(){
$.ajax({
url: "url_a",
type: "post",
dataType: "html",
cache: false,
success: function(data){
},
error:function(){
}
});
}
function b(){
$.ajax({
url: "url_b",
type: "post",
dataType: "html",
cache: false,
success: function(data){
},
error:function(){
}
});
}
最佳答案
由于 ajax 调用是异步的,因此如果您希望第二个 ajax 调用在第一个调用完成之前不启动,则需要手动对 ajax 调用进行排序。
Promise 特别适合序列化异步操作,并且可以使其变得非常简单。幸运的是,jQuery 内置了 Promise,并且每个 Ajax 操作都已返回可用于此目的的 Promise:
$.ajax(...).then(function(result1) {
// make 2nd ajax call when the first has completed
return $.ajax(...);
}).then(function(result2) {
// success of both ajax calls here
}, function(err) {
// error here
});
或者,如果您使 a()
和 b()
都从它们的 ajax 调用中返回 jQuery ajax promise ,那么您可以这样做:
a().then(b);
并且,c()
可能只是:
function c() {
return a().then(b);
}
因此,如果您想在没有 a()
和 b()
的情况下进行函数调用来包含这两个 Ajax 调用,则应该让它返回一个 Promise:
function c() {
return $.ajax(...).then(function(result1) {
// make 2nd ajax call when the first has completed
return $.ajax(...);
})
}
然后,您可以像这样调用 c()
:
c().then(function(result) {
// success here
}, function(err) {
// error here
});
<小时/>
下面是返回 Ajax Promise 的函数示例:
function test() {
return $.ajax("http://www.test.com/api/test");
}
<小时/>
现在,您已经添加了实际的 ajax 代码,您只需添加一个返回即可:
function a(){
return $.ajax({
url: "url_a",
type: "post",
dataType: "html",
cache: false
});
}
function b(){
return $.ajax({
url: "url_b",
type: "post",
dataType: "html",
cache: false
});
}
function c() {
return a().then(b);
}
关于javascript - 通过 Ajax 调用顺序运行两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332491/