簡體   English   中英

在jQuery.when中鏈多個“then”

[英]Chain multiple “then” in jQuery.when

我有一個像這樣的功能:

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 ,他們也可以鏈接更多的回調,例如:

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。

我怎么能在JS中做到這一點?

.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返回任何內容,因此新的延遲對象沒有參數。 看這個例子:

$.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 ,它將按預期工作。

$.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請求:

$.ajax({...}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
}).then(function(){
    return $.ajax({...});
});

這也可以在循環中輕松完成。 每個.then都可以訪問上一個請求中返回的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM