jQuery $.when() 其中一个参数来自异步 "Deferred pipe"

标签 jquery asynchronous jquery-deferred decoupling

jQuery 的一次使用 Deferred系统带有 $.when()功能。它需要可变数量 Promise's and will do something when they all解决(or when the first拒绝。)

所以如果你想对两个Ajax进行操作JSON例如您可以执行的查询:

var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');

$.when(funkyPromise, awesomePromise).then(function() {
  /* do something amazing with the two objects */
}, function() {
  /* at least one of the services failed this time */
});

您可以使用 jQuery 做的另一件事 Deferred系统的目的是通过“链接”来自一个Deferred的数据来建立数据管道。通过另一个使用 pipe最终使用之前的方法:

$.getJSON('http://funky.json.service.com')
  .pipe(funkytoFunkier);
}).done(function(funkyData) {
    /* we now have a funkier version of what the web service gave us */
});

一切都非常异步和解耦。

但是如果我想使用 $.when() 会发生什么?关于两个异步Promise但我们还没有其中之一,因为它将通过 pipe 来实现异步?

var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');

// run "funky" through an asynchronous "pipe" to get "funkier"
//
// ... but ... how ??

$.when(funkyier, awesome).then(function() {
  /* do something amazing with the two objects */
}, function() {
  /* at least one of the services failed this time */
});

那么中间部分是什么?

  • 它是否非常明显而我却看不到?
  • 这有可能吗,但是非常微妙和棘手?
  • 是否有一些新的“倒置”等价物 pipe()$.when()等等让它变得更容易?

最佳答案

pipe()返回一个新的 promise ,该 promise 将在管道解析时得到解决,因此您只需编写:

var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');

$.when(funkyPromise.pipe(funkytoFunkier), awesomePromise).then(function() {
  /* do something amazing with the two objects */
}, function() {
  /* at least one of the services failed this time */
});

请注意,从 jQuery 1.8 开始,then()pipe() 执行相同的操作,因此这两种方法基本上可以互换。

关于jQuery $.when() 其中一个参数来自异步 "Deferred pipe",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282309/

相关文章:

javascript - 过滤 dxdatagrid 的查找列值

c++ - 跟进: Asynchronous off-screen query performance

c# - Fire and Forgot 的异步/等待方法

javascript - 具有多个依赖项的 jQuery ajax 调用链

javascript - jQuery:链接动画和 AJAX 请求

javascript - 来自单个请求的 ajax 请求数组

jquery - 与 fancybox 一起使用时如何在 jwplayer 上获取全屏视频

jquery - 为 10+ 以上的有序列表元素着色

jquery - 使用 JQuery 突出显示一行中的第一列

javascript - 管理 node-postgres 查询