2016-12-28 36 views
0

我面臨延遲使用的問題,其中2個嵌套的函數應該等待對方實際以錯誤的順序靜靜地運行。 我不能'找出我在哪裏混合回報的承諾。推遲jQuery的問題

所以這裏是我試圖實現的。在移動Cordova應用程序中,當用戶進入遊戲視圖時,我有一個函數可以在WebSql中下載問題,然後我想要檢索一個問題,然後使用我的滑塊函數加載內容。 因此,我在.done()事件中嵌套了getQuestion函數。

router.addRoute('game', function() { 
     'use strict'; 
     //Reload Question List when User enter the Game view. 
     questionService.initialize().done(
     //Now we got question, initialize the Game View 
     questionService.getQuestion().done(
      function (data) { 
      console.log(data); 
      slider.slidePage(new GameView(data).render().$el); 
      }) 
    ); 

這裏是我如何在這兩個函數中使用$.Deferred()。首先我宣佈我的$.Deferred(),並在函數結束時返回承諾。

但我在下面的代碼getQuestion()不等待initialize()函數在開始之前結束。

我在哪裏混淆了我的承諾回報?

var getQuestions = function(param) { 
    var deferred = $.Deferred(); 
    param = param; 
    $.ajax({ 
     type: 'POST', 
     url: 'myserver', 
     data: { 
      region: uRegion 
     }, 
     success: function(value, status) { 
      //do something with value 
      this.db = window.openDatabase('database details'); 
      this.db.transaction(function(tx) { 
       storeQuestion(tx); 
      }, function(error) { 
       deferred.reject('Transaction error: ' + error); 
      }, function() { 
       //Transaction success 
       deferred.resolve(); 
      }); 
     }, 
     error: function(textStatus, exception) {} 
    }); 
    return deferred.promise(); 
}; 

回答

0

您未通過成功回調處理程序。根據當前的實施,您立即調用getQuestion()

使用匿名函數,休息以其優良的

//Reload Question List when User enter the Game view. 
questionService.initialize().done(function(){ 
    //Now we got question, initialize the Game View 
    questionService.getQuestion().done(
     function (data) { 
     console.log(data); 
     slider.slidePage(new GameView(data).render().$el); 
     }) 
});