Javascript then() 链接 - Deferred 第二个 then() 对应于哪个

Javascript then() chaining - which Deferred does the second then() correspond to?

本文关键字:then 于哪个 第二个 链接 Javascript Deferred      更新时间:2023-12-07

1( 我有一个 jquery 链 then((,像这样:

someAjax().then(function(val) { console.log("done 1: " + val); return val + 1; },
                function(val) { console.log("fail 1: " + val); return val + 2; },
                function(val) { console.log("prog 1: " + val); return val + 3; }
         ).then(function(val) { console.log("done 2: " + val) },
                function(val) { console.log("fail 2: " + val) },
                function(val) { console.log("prog 2: " + val) }
         )

我知道第一个then((的三个函数(三个参数(对应于someAjax((中延迟对象的状态。

但是,我不明白,第二个函数(args(对应于哪个延迟对象?例如,如果(或者有可能(第一个 then(( 的三个函数中的每一个都可以返回自己的 Deferred 对象,该怎么办?

我觉得我可能误解了这里的一些东西。感谢任何澄清。

//

/

2(我还有另一个这样的链接:

$.getJSON(url).then(
                doneFunction1,
                errorFunction1
            ).then(
                doneFunction2
            });

doneFunction1 看起来像这样:

function doneFunction1(val){
   if(val > 1)
      return $.ajax(url2);
}

因此,如您所见,这并不总是返回承诺,具体取决于val。如果它没有返回承诺(例如 val <1(,那么第二个如何进行?这会导致错误吗?因为据我了解,没有承诺可以调用 then((。我的猜测是,它可能只是调用第一个$.getJSON承诺的 then((,但我可能是错的。

基本上,我试图在"val <1"时根本不有第二个then()。可能吗?

您可以只返回已解决或拒绝的延迟

function doneFunction1(val){
    if(val > 1) {
        return $.ajax(url2);
    } else {
        var def = $.Deferred();
        return def.reject(); // or def.resolve('something'); to hit the success handler
    }
}
$.getJSON(url).then(
    doneFunction1,
    errorFunction1
).then(
    doneFunction2,
    errorFunction2 // only needed if you want to catch the error
});