6

在 Javascript 中,我有两个异步数据请求:

$.getJSON('http://foo.com', fooQuery, fooSuccess(data));
$.getJSON('http://bar.com', barQuery, barSuccess(data));

和两个回调来处理接收到的数据:

fooSuccess(data) { // Stuff }
barSuccess(data) { // More Stuff }

如何确保 barSuccess 仅在 fooSuccess 完成后执行?

笔记:

  • 我想保持数据请求原样:异步和非阻塞(因为服务器响应可能需要一段时间)。
  • 但是,我希望处理数据的回调按顺序执行。也就是说,我不想在 fooSuccess 完成之前执行 barSuccess。

非常感谢您的智慧和帮助!

4

4 回答 4

5

以下是使用 ajax 请求返回的 jQuery 延迟对象的方法。

var fooDfd = $.getJSON('http://foo.com', fooQuery);
var barDfd = $.getJSON('http://bar.com', barQuery);

fooDfd.then(function(fooData){
    fooSuccess(fooData);
    barDfd.then(barSuccess);
});

​</p>

于 2012-12-28T00:53:41.093 回答
5

最好的方法是when().done()像这样使用 jQuery 功能:

$.when(
    $.getJSON('http://foo.com', fooQuery, fooSuccess(data)), 
    $.getJSON('http://bar.com', barQuery, barSuccess(data))
).done(function(arg1, arg2){
    fooSuccess(arg1);
    barSuccess(arg2);
});

这允许同时执行 AJAX 请求并保证在done()所有请求成功完成后执行该函数。

于 2012-12-28T00:55:03.360 回答
1

I'm follow this very interesting post from a half an hour ago, when appear the elegant solution presented by @Mike Brant I quickly was to dive in the jquery library to see how the magic is made. Don't you? I recommend, is very interesting! BTW I think we don't need all that magic, not in this case, we have two asynchronous calls handlers(functions), no matter which end first, we need to know when the second end, then all we need is a third function that will be called by the two handlers and act when all the data is ready. I know this approach will vaste four or five lines more of code than the elegant jquery solution, but at the end our brain and soul will be in better condition. Sorry my english.

于 2012-12-28T01:46:02.337 回答
-1

barSuccess调用放入fooSuccess成功回调中。

fooSuccess(data){
  jQuery.ajax({
    data: data,
    success: function(response){
      barSuccess(data) //should still be in scope, I think?
    }
  }
}
于 2012-12-28T00:40:49.797 回答