在 jQuery.when 中链接多个“then”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17216438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chain multiple "then" in jQuery.when
提问by Lucas Sampaio
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 */;
}
So, when someone uses do_something
, they can also chain more callbacks, like:
因此,当有人使用 时do_something
,他们还可以链接更多回调,例如:
do_something().then(function(_foo_2, _bar_2, _baz_2) {
console.log(_foo_2, _bar_2, _baz_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.
问题是我不知道如何绕过从do_something_else
描述的匿名函数的原始返回。我不想接收列表,而是接收位置参数,因此“当 foo”向 do_something_else 的 _foo 插入一些值,然后将相同的值插入 _foo_2。
How can I do it in JS?
我怎么能在JS中做到这一点?
回答by Kevin B
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.
在里面使用匿名函数.then
并传递您要传递的参数。我替换.then
为.done
因为.then
在这种情况下你不需要。
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 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:
.then 实际上创建了一个新的延迟对象并将其发送到链。由于您没有从 返回任何内容.then
,因此新的延迟对象没有参数。看这个例子:
$.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
});
If you instead just used .done
, it would work as expected.
如果您只是使用.done
,它将按预期工作。
$.when($.Deferred().resolve(2), $.Deferred().resolve(4))
.done(function(a,b) {
console.log(a,b);
}).done(function(a,b) {
console.log(a,b);
});
The most common use for .then
is chaining ajax requests:
最常见的用途.then
是链接 ajax 请求:
$.ajax({...}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
});
which can also be easily done in a loop. Each .then
will have access to the returned data from the previous request.
这也可以在循环中轻松完成。每个人.then
都可以访问从前一个请求返回的数据。