0
私はjQueryの約束を使ってサーバー上のいくつかの変更を追跡します。私もtypescriptを使うので、私の例はtypescriptです。予期しない "then" jQueryの約束による呼び出しの順序
私は変更を追跡するために、次のメソッドを使用します。
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
メソッドを呼び出します。ここで
は私が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/