javascript - 如何使用 jQuery promises 链接三个异步调用?

标签 javascript jquery asynchronous deferred

我需要以同步方式进行三个 HTTP 调用,如何将数据从一个调用传递到另一个调用?

function first()
{
   ajax()
}

function second()
{
   ajax()
}

function third()
{
   ajax()
}


function main()
{
    first().then(second).then(third)
}

我尝试将 deferred 用于这两个函数,我想出了一个部分解决方案。我可以将它扩展为三个功能吗?

function first() {
    var deferred = $.Deferred();
     $.ajax({

             "success": function (resp)
             {

                 deferred.resolve(resp);
             },

         });
    return deferred.promise();
}

function second(foo) {
     $.ajax({
            "success": function (resp)
            {
            },
            "error": function (resp)
            {
            }
        });
}


first().then(function(foo){second(foo)})

最佳答案

在每种情况下,返回由 $.ajax() 返回的 jqXHR 对象。

这些对象与 Promise 兼容,因此可以与 .then()/.done()/.fail()/链接.always()

.then() 是您在这种情况下想要的,与问题中的完全一样。

function first() {
   return $.ajax(...);
}

function second(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function third(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function main() {
    first().then(second).then(third);
}

参数 datatextStatusjqXHR 源自上一个函数中的 $.ajax() 调用, IE。 first() 提供 second()second() 提供 third()

DEMO (使用 $.when('foo') 代替 $.ajax(...) 来交付已实现的 promise )。

关于javascript - 如何使用 jQuery promises 链接三个异步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16026942/

相关文章:

javascript - NodeJS Passport BasicStrategy 未经授权

javascript - 路径上的 d3.js 工具提示

python - python 如何绕过我之前的代码而先运行后面的代码?

javascript - Angular 日期最小值未被强制执行

javascript - 动态 JSONP 方法

javascript - 根据键值显示 JSON 文件中的值

javascript - jQuery 如何进行方法链接?

jquery - 短页时,粘性 header 会导致页 "jumps"

c# - 如何从 List.ForEach C# 进行异步调用

file - 如何使用 tokio::fs 复制文件