2014-02-14 72 views
2

我有以下條件首先調用syncAnalytics。在這個函數裏面,還有另外一個函數,retreiveAnalyticsData,用來檢索本地存儲的數據。函數不同步返回值

但是在從retreiveAnalyticsData返回值之前,函數syncAnalytics的其餘部分被執行。

DemoModule.factory('ApplicationAnalytics', function ($http, $location, DBO) { 
    return { 
     syncAnalytics: function() { 
      console.log("syncAnalytics called");// Getting displayed 1st 
      // Retrieve analytics data available data from db 
      var inputData = this.retreiveAnalyticsData(); 
      console.log("Input Data : " + JSON.stringify(inputData)); // Getting displayed 4th 
     },  
     retreiveAnalyticsData: function() { 
      console.log('retreiveAnalyticsData called');// Getting displayed 2nd 
      // Select all rows from app_analytics table in db 
      var selectQuery = "SELECT * FROM app_analytics"; 
      var analyticsData = []; 
      DBO.execQry(selectQuery, function (results) { 
       var len = results.rows.length, 
        i; 
       for (i = 0; i < len; i++) { 
        analyticsData.push(results.rows.item(i).text); 
       } 
       console.log(analyticsData); //Getting displayed 5th 
       return analyticsData; 
      }); 
      console.log('retreiveAnalyticsData ended');// Getting displayed 3rd 
     } 
    }; 
}); 

所以基本上:

var inputData = this.retreiveAnalyticsData(); //This should be executed before the below line. 
console.log("Input Data : " + JSON.stringify(inputData)); // Getting displayed 4th 

任何有識之士將不勝感激。

注意:我正在使用AngularJS

回答

3

DBO.execQry是一個異步函數。你可能會看到這個,因爲回調模式 - 例如execQry的第二個參數是一個在execQry準備好檢索數據時調用的函數。我想你看到的是,console.log('retreiveAnalyticsData結束');在console.log(analyticsData)之前打印出來;

如何處理?

1)舊校園的方法是使用一個回調函數:

syncAnalytics: function() { 
    this.retreiveAnalyticsData(function(inputData){ 
     console.log("Input Data : " + JSON.stringify(inputData)); 
    }); 
}, 

retreiveAnalyticsData: function (callback) { 
    var selectQuery = "SELECT * FROM app_analytics"; 
    var analyticsData = []; 
    DBO.execQry(selectQuery, function (results) { 
     var len = results.rows.length, 
     for (var i = 0; i < len; i++) { 
     analyticsData.push(results.rows.item(i).text); 
     } 
     callback(analyticsData); 
    }); 
} 

但這種方式有很多缺點。如果您想要處理錯誤或需要進行多個異步調用或將它們同步到一起,該怎麼辦?所以我們來到諾言模式。

2)無極模式由$q

syncAnalytics: function() { 
    this.retreiveAnalyticsData().then(function(inputData){ 
     console.log("Input Data : " + JSON.stringify(inputData)); 
    }); 
}, 

retreiveAnalyticsData: function() { 
    var selectQuery = "SELECT * FROM app_analytics"; 
    var analyticsData = []; 
    var deferred = $q.defer(); 
    DBO.execQry(selectQuery, function (results) { 
     var len = results.rows.length, 
     for (var i = 0; i < len; i++) { 
     analyticsData.push(results.rows.item(i).text); 
     } 
     deferred.resolve(analyticsData); 
    }); 
    return deferred.promise; 
} 
+0

真棒..將檢查了這一點,讓你KNW .. –