2017-07-02 19 views
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/

答えて

3

あなたが代わりにAjaxの約束を連鎖のタイムアウトによって解決約束戻っている:

... 

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

... 
関連する問題