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 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
});
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);
});
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({...});
});
which can also be easily done in a loop. Each .then
will have access to the returned data from the previous request.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…