2015-09-10 41 views
0

我需要在數據庫中插入x行。這裏是我的代碼:在sqlite插入角度等待諾言

dataFactory.insertData = function (responseData) 
     { 
      var q = $q.defer(); 
      var rows = 0; 
      $.each(responseData, function (index, value) 
      { 
       var query = "insert or ignore into ..."; 
       $cordovaSQLite.execute(db, query).then(function (res) 
       { 
        rows += 1; 
       }, function (err) 
       { 
        console.error(err); 
       }); 
      }); 
      q.resolve(rows); 
      return q.promise; 
     }; 

如何等待所有插入完成後再調用解決?我相信在插入所有行之前,q.promise會得到解決。

+0

我認爲每個應用檢查裏面像if(rows === responseData.length)意味着所有插入db的數據。 –

+0

那好,但不是問題。所有插入完成後,我都想解決承諾。我認爲在插入所有行之前會解析該解析。 –

+0

解決上述檢查中的承諾。 –

回答

0

試試下面的代碼

dataFactory.insertData = function (responseData) 
      { 
       var q = $q.defer(); 
       var rows = 0; 
       var howManyRecordProcessed =0; 
       $.each(responseData, function (index, value) 
       { 
        //... prepare data... 
        $cordovaSQLite.execute(db, query).then(function (res) 
        { 
         //response after db save 
         howManyRecordProcessed++; //increment variable 
         if(howManyRecordProcessed === responseData.length) 
{ 
    //resolve here 
    q.resolve(rows); 
} 
         rows += 1; 
        }, function (err) 
        { 
         //if some error occured. 
         howManyRecordProcessed++; 
         console.error(err); 
        }); 
       }); 
       q.resolve(rows); 
       return q.promise; 
      }; 

OR可能是移動DB存儲邏輯到另一個將返回承諾當所有保存。