javascript - 通过 Ajax 调用顺序运行两个函数

标签 javascript jquery ajax

我有两个函数,其中有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/

相关文章:

javascript - 使用 Jquery 和 cookie.split 从 cookie 中删除一个值

javascript - 减慢 <a href =""> 的执行速度

javascript - Chrome 忽略我的 if 语句

javascript - DOJO:DataGrid 增量加载不起作用

javascript - 在 Hangman Game 中屏幕重置后显示我的获胜图像

javascript - 如何从数据库中获取当前日期到最近 5 天的值

javascript - 我需要在以下 JavaScript 代码中导出辅助函数吗?

javascript - 菜单项未正确显示为大型菜单

javascript - MVC 在局部 View 中使用 JS

html - 加载页面后如何跟踪 HTML 页面上内容的变化