72

我需要以同步方式进行三个 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)})
4

9 回答 9

89

In each case, return the jqXHR object returned by $.ajax().

These objects are Promise-compatible so can be chained with .then()/.done()/.fail()/.always().

.then() is the one you want in this case, exactly as in the question.

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);
}

Arguments data, textStatus and jqXHR arise from the $.ajax() call in the previous function, ie. first() feeds second() and second() feeds third().

DEMO (with $.when('foo') to deliver a fulfilled promise, in place of $.ajax(...)).

于 2013-04-16T19:43:55.817 回答
40

在 jQuery 中使用 Promise 时,实际上有一种更简单的方法。看看以下内容:

$.when(
    $.ajax("/first/call"),
    $.ajax("/second/call"),
    $.ajax("/third/call")
    )
    .done(function(first_call, second_call, third_call){
        //do something
    })
    .fail(function(){
        //handle errors
    });

只需将所有调用链接到 $.when(...) 调用并处理 .done(...) 调用中的返回值。

如果您愿意,这里有一个演练:http: //collaboradev.com/2014/01/27/understanding-javascript-promises-in-jquery/

于 2014-01-27T23:21:00.557 回答
36

回复很晚,但我想答案缺少一些直接的链接代码。使用 jquery 中的 Promise 支持链接事件非常简单。我使用以下链接:

$.ajax()
.then(function(){
   return $.ajax() //second ajax call
})
.then(function(){
   return $.ajax() //third ajax call
})
.done(function(resp){
   //handle final response here
 })

它很简单,没有复杂的 for 循环或多个嵌套回调。

于 2017-04-02T20:56:58.220 回答
15

它比这简单得多。

$.ajax已经返回了一个承诺(延迟对象),所以你可以简单地写

function first() {
    return $.ajax(...);
}
于 2013-04-16T00:47:16.180 回答
6

最好的方法是为此创建一个可重用的函数。这甚至可以使用一行代码来完成reduce

function chainPromises(list) {
    return list.reduce((chain, func) => chain ? chain.then(func) : func(), null);
}

这个函数接受一个回调数组,它返回一个承诺对象,就像你的三个函数一样。

示例用法:

chainPromises([first, second, third]).then(function (result) {
    console.log('All done! ', result);
});

这样 的结果first也将自动成为 的参数second,所以基本上会发生这样的事情:

first().then(function(res1) { return second(res1) })
       .then(function(res2) { return third(res2)  })
       .then(function(result) { console.log('All done! ', result) });

当然,您可以根据需要向数组中添加任意数量的函数。

于 2017-01-29T12:52:58.317 回答
6

您可以以更实用的方式编写它:

[function() { return ajax(...)}, function(data) { return ajax(...)}]
.reduce(function(chain, callback) { 
  if(chain) { 
    return chain.then(function(data) { return callback(data); });
  } else {
    return callback();
  }
}, null)
于 2016-01-26T15:48:49.877 回答
4

我在这里找到了一个好看的解决方案:How do I chain a sequence of deferred functions in jQuery 1.8.x?

这是我自己实现的类似方法,有点丑陋但可能有效。它将每个方法的结果广播为返回的承诺对象上的“进度更新”。

  $.chain = function() {
      var defer = $.Deferred();
      var funcs = arguments;
      var left = funcs.length;
      function next(lastResult) {
          if(left == 0) {
              defer.resolve();
              return;
          }
          var func = funcs[funcs.length - left]; // current func
          var prom = func(lastResult).promise(); // for promise will return itself,
                                       // for jquery ojbect will return promise.
          // these handlers will be launched in order we specify them
          prom.always(function() {
              left--;
          }).done(function(ret) {
              defer.notify({
                  idx: funcs.length-left,
                  left: left,
                  result: ret,
                  success: true,
              });
          }).fail(function(ret) {
              defer.notify({
                  idx: funcs.length-left,
                  left: left,
                  result: ret,
                  success: false,
              });
          }).always(function(ret) {
              next(ret);
          });
      }
      next();
      return defer.promise();
  };

如何根据您的情况使用它?也许不漂亮,但它应该工作:

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

var id;

funciton second() {
    return ajax(id, ...);
}

function third() {
    return ajax(id, ...);
}

$.chain(first, second, third).progress(function(p) {
    if(p.func == first)
        id = p.result.identifier;
}).then(function() {
    alert('everything is done');
});

或者您可以从first函数中分配该 id 变量。

或者,如果您只需要前一个函数的结果,您可以使用这种方法:

function first() {
    return ajax(...);
}
function second(first_ret) {
    return ajax(first_ret.id, ...);
}
function third(second_ret) {
    return ajax(second_ret.something, ...);
}
于 2015-09-23T00:33:04.760 回答
0

以下似乎有效,并允许函数列表是动态的:

<html>
  <head>
  <title>demo chained synchronous calls</title>
  </head>
  <body>

  <script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
  <script type="text/javascript">
    function one(parms) {
        console.log('func one ' + parms);
        return 1;
    }

    function two(parms) {
        console.log('func two ' + parms);
        return 2;
    }

    function three(parms) {
        console.log('func three ' + parms);
        return 3;
    }

    function four(parms) {
        console.log('func four ' + parms);
        return 4;
    }

    var funcs = ['one', 'two', 'three', 'four'];
    var rvals = [0];

    function call_next_func() {
        if (funcs.length == 0) {
            console.log('done');
        } else {
            var funcname = funcs.shift();
            console.log(funcname);
            rvals.push(window[funcname](rvals));
            call_next_func();
        }
    }

    $(document).ready(function($){
        call_next_func();
    });
  </script>

  </body>
</html>

于 2016-12-02T23:25:23.120 回答
-1

要链接 jquery ajax 调用,我做了:

function A(){
     return $.ajax({
      url: url,
      type: type,
      data: data,
      datatype: datatype,
      success: function(data)
      {
        code here
      }
    });
   }

   function B(){
     return $.ajax({
      url: url,
      type: type,
      data: data,
      datatype: datatype,
      success: function(data)
      {
        code here
      }
    });
   }

   function C(){
     return $.ajax({
      url: url,
      type: type,
      data: data,
      datatype: datatype,
      success: function(data)
      {
        code here
      }
    });
   }

   A().done(function(data){
     B().done(function(data){
        C();
     })
   });
于 2018-06-18T05:43:39.153 回答