问题描述
所以我的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
进行交互或保证会退回。来自:
But, it will interact with a Deferred
or promise that's returned. From the paragraph starting with "As of jQuery 1.8":
因此,您可以使用 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
});
这篇关于jQuery.Deferred()。然后,如何解决多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!