链多个“然后”在jQuery.when [英] Chain multiple "then" in jQuery.when
问题描述
我有一个类似这样的函数:
I have a function that does something like this:
function do_something() {
// some code
return $.when(foo, bar, baz).then(do_something_else);
}
function do_something_else(_foo, _bar, _baz) {
// do something else
return /* the original inputs */;
}
所以,当有人使用 do_something $ c时$ c>,他们还可以链接更多回调,例如:
So, when someone uses do_something
, they can also chain more callbacks, like:
do_something().then(function(_foo_2, _bar_2, _baz_2) {
console.log(_foo_2, _bar_2, _baz_2);
});
问题是我不知道如何绕过 do_something_else
到所描述的匿名函数。我不想收到列表,而是接收位置参数,所以当foo向do_something_else的_foo插入一些值,然后相同的值转到_foo_2。
The problem is that I don't know how to bypass the original return from do_something_else
to the anonymous function described. I don't want to receive a list, but positional arguments instead, so "when foo" inserts some value to do_something_else's _foo and then the same value goes to _foo_2.
我怎么能在JS中做到这一点?
How can I do it in JS?
推荐答案
在 .then $中使用匿名函数c $ c>并传递您要传递的参数。我正在用
.done
替换 .then
,因为你不需要 .then
在这种情况下。
Use an anonymous function inside of .then
and pass the parameters that you want to pass. I'm replacing .then
with .done
because you don't need .then
in this case.
function do_something() {
// some code
return $.when(foo, bar, baz).done(function(_foo_2, _bar_2, _baz_2){
do_something_else.apply(this,_foo_2);
});
}
。然后实际创建一个新的延迟对象并将其发送到链。由于您没有从 .then
返回任何内容,因此新的延迟对象没有参数。请参阅此示例:
.then actually creates a new deferred object and sends that to the chain. Since you didn't return anything from .then
, the new deferred object has no arguments. See this example:
$.when($.Deferred().resolve(2), $.Deferred().resolve(4))
.then(function(a,b) {
console.log(a,b); // 2,4
return $.Deferred().resolve(a,b,6);
}).then(function(a,b,c) {
console.log(a,b,c); // 2,4,6
});
如果您只使用 .done
,它会按预期工作。
If you instead just used .done
, it would work as expected.
$.when($.Deferred().resolve(2), $.Deferred().resolve(4))
.done(function(a,b) {
console.log(a,b);
}).done(function(a,b) {
console.log(a,b);
});
.then
的最常见用途是链接ajax请求:
The most common use for .then
is chaining ajax requests:
$.ajax({...}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
});
也可以在循环中轻松完成。每个 .then
都可以访问上一个请求中返回的数据。
which can also be easily done in a loop. Each .then
will have access to the returned data from the previous request.
这篇关于链多个“然后”在jQuery.when的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!