gpt4 book ai didi

javascript - jQuery promise 出现意外的 "then"调用顺序

转载 作者:行者123 更新时间:2023-11-28 17:54:00 24 4
gpt4 key购买 nike

我使用 jQuery Promise 来跟踪服务器上的一些更改。我也使用 typescript ,所以我的例子是 typescript 。

我使用以下方法来跟踪更改:

startObserve(): JQueryPromise<void> {
console.info("initializing...");

const that = this;
let countdown = 3;

return this.loadData()
.then(baseData => {
const checkChanges = () => {
const d = $.Deferred();
d.then(() => {
console.info("checking changes...");

return that.loadData()
.then(data => {
countdown--; // emulate check logic

console.info("next interation! countdown:", countdown);

if (countdown === 0)
return null;

return checkChanges();
});
});
setTimeout(d.resolve, 250);
return d.promise();
};

return checkChanges();
});
}

所以我只是递归调用 checkChanges 方法,该方法返回新的 promise ,直到检测到某些更改。

以下是我尝试使用 startObserve 方法的方法:

    this.startObserve()
.then(() => {
console.info("change detected! we can continue!");
}).fail(() => {
console.error("something is very wrong!");
});

我期望得到以下输出:

initializing...
checking changes...
next interation! countdown: 2
checking changes...
next interation! countdown: 1
checking changes...
next interation! countdown: 0
**change detected! we can continue!**

但这就是我得到的:

initializing...
checking changes...
**change detected! we can continue!**
next interation! countdown: 2
checking changes...
next interation! countdown: 1
checking changes...
next interation! countdown: 0

对我来说,这看起来有点奇怪。我哪里错了?这是显示问题的 jsfiddle:https://jsfiddle.net/4dofznqL/1/

最佳答案

您返回的是通过超时解决的 promise ,而不是链接 ajax promise :

...

const checkChanges = () => {
const d = $.Deferred();
setTimeout(d.resolve, 250);

return d.then(() => {
console.info("checking changes...");

return that.loadData()
.then(data => {
countdown--;

console.info("next interation! countdown:", countdown);

if (countdown === 0)
return null;

return checkChanges();
});
});
};

...

关于javascript - jQuery promise 出现意外的 "then"调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869908/

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