Luc*_*aio 34 javascript jquery jquery-deferred
我有一个像这样的功能:
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 */;
}
Run Code Online (Sandbox Code Playgroud)
因此,当有人使用时do_something
,他们也可以链接更多回调,例如:
do_something().then(function(_foo_2, _bar_2, _baz_2) {
console.log(_foo_2, _bar_2, _baz_2);
});
Run Code Online (Sandbox Code Playgroud)
问题是我不知道如何绕过原来的返回do_something_else
来描述匿名函数.我不想收到列表,而是接收位置参数,所以"当foo"为do_something_else的_foo插入一些值,然后相同的值转到_foo_2.
我怎么能在JS中做到这一点?
use*_*654 66
在其中使用匿名函数.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);
});
}
Run Code Online (Sandbox Code Playgroud)
.然后实际创建一个新的延迟对象并将其发送到链.由于您没有返回任何内容.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
});
Run Code Online (Sandbox Code Playgroud)
如果您只是使用.done
它,它将按预期工作.
$.when($.Deferred().resolve(2), $.Deferred().resolve(4))
.done(function(a,b) {
console.log(a,b);
}).done(function(a,b) {
console.log(a,b);
});
Run Code Online (Sandbox Code Playgroud)
最常见的用途.then
是链接ajax请求:
$.ajax({...}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
}).then(function(){
return $.ajax({...});
});
Run Code Online (Sandbox Code Playgroud)
这也可以在循环中轻松完成.每个人.then
都可以访问上一个请求中返回的数据.
归档时间: |
|
查看次数: |
48176 次 |
最近记录: |