gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:16:51 25 4
gpt4 key购买 nike

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) }
)

据我了解,first then() 的三个函数(三个参数)对应于 someAjax() 中的 Deferred 对象的状态。

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

我觉得我可能误解了这里的某些内容。感谢任何澄清。

/////////////////////////////////////////////////////////////////////////////////////////////

2)我有另一个像这样的链接:

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

doneFunction1 看起来像这样:

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

因此,正如您所看到的,这并不总是返回一个 promise ,具体取决于 val。如果它不返回 Promise(比如 val < 1),那么第二个如何继续?这会导致错误吗?因为据我了解,没有 Promise 可以调用 then() 。我的猜测是它可能只是调用 $.getJSON 第一个 Promise 的 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
});

关于Javascript then() 链接 - 第二个 then() 对应哪个 Deferred?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com