jQuery.Deferred()。然后,如何解决多个参数 [英] jQuery.Deferred().then, how to resolve with multiple parameters

查看:137
本文介绍了jQuery.Deferred()。然后,如何解决多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的API期望当特定的延迟被解析时它会得到2个参数。

So my API expects that when a particular deferred is resolved it gets 2 params.

fn().done(function(arg1, arg2) {
  console.log(arg1, arg2);
}).fail(function(err) {
  console.error(err);
});

现在与上面的 fn 函数有关,它需要先等待其他一些延迟返回才能解决。

Now relating to the fn function above, it needs to first wait for some other deferred to return before resolve.

function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return [1, 2];
  });
}

但这不起作用,因为 arg1 将来自 [1,2] arg2 将是 undefined 。我无法弄清楚如何从 Deferred.then()返回第一个成功过滤器函数参数,以便生成的管道延迟解析多个参数。

But this is not working, because arg1 will come as [1, 2] and arg2 will be undefined. I cannot figure out how to return something from Deferred.then() first success filter function argument so that the resulting piped deferred resolves with multiple arguments.

当然我可以这样做:

function fn() {
  var done = $.Deferred();
  other().done(function(){
    done.resolve(1, 2);
  }).fail(function(){
    done.reject.apply(done, arguments);
  });
  return done.promise();
}

但这并不像使用那样优雅。那么()我现在每次都需要担心负面的失败案例API,即使我知道我只是通过管道被拒绝的状态。

But that is not nearly as elegant as using .then() and I now need to worry about the negative failure case API each time even though I know that I'm merely piping the rejected state through.

是的,我还可以更改 fn() api以解决数组,但我真的希望有一个优雅的解决方案。

And yes, I could also change fn() api to resolve with an array, but I am really hoping there is an elegant solution to this.

推荐答案

您必须调用 resolve() reject()以传递多个参数。

You will have to invoke resolve() or reject() in order to pass multiple arguments.

.then() doesn不包括传播返回集合的任何机制。它只是将集合保持为第一个参数。

.then() doesn't include any mechanisms for "spreading" a returned collection. It'll just keep the collection intact as the 1st argument.

但是,它将与 Deferred 进行交互或保证会退回。来自从jQuery 1.8开始开头的段落

But, it will interact with a Deferred or promise that's returned. From the paragraph starting with "As of jQuery 1.8":


这些过滤器函数可以返回一个新值,传递给promise的.done()或.fail()回调,或者他们可以返回另一个可观察对象(延期,承诺等),它会将其已解决/拒绝的状态和值传递给承诺的回调

因此,您可以使用 other()的示例作为 fn()的基础保持它相当简洁与另一个 Deferred()

So, you could use your example of other() as the basis for fn() to keep it fairly succinct with another Deferred():

function fn() {
    return other().then(function () {
        return $.Deferred().resolve(1, 2).promise();
    });
}

fn().then(function (a, b) {
    console.log(arguments.length, a, b); // 2 1 2
});

http://jsfiddle.net/cqac2/

这篇关于jQuery.Deferred()。然后,如何解决多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆