2016-01-20 64 views
0

這是我的代碼片段:AngularJS:從工廠,如何調用另一個函數在一個週期

_service.factory('$opSQL', [ '$rootScope', '$cordovaSQLite', 

    function($rootScope, $cordovaSQLite){ 

     var db = $cordovaSQLite.openDB( "my.db"); 
     var dbURL = dbConfig.remoteUrl; 

     var opSQL = { 
      deleteRow : function(row) { 

       var strQuery = "DELETE FROM UpdateTo WHERE id = ? ;"; 
       $cordovaSQLite.execute(db, strQuery, [row.id]) 
       .then(
        function(res) { console.log (JSON.stringify(row.id)); }, 
        function (err) { console.log (JSON.stringify(err)); }); 
      }, 

      sendToServer : function(tmp) { 
       // where tmp = [ { "id":1, "other"="..." }, { "id":2, "other"="..." } ... ] 
       for(x in tmp) 
       { 
        opSQL.deleteRow(tmp[x]); 
       } 
      } 
     } 
     return opSQL; 
    } 
]); 

我認爲這個問題是SQLite中執行異步因爲查詢完成成功,但在控制檯我只讀取列表的第一個ID。

如何解決這個問題?

+0

您只輸出'row.id'。你的期望是什麼? – lex82

+0

當我調用fn「sendToServer」時,我期待看到所有循環的id,但輸出總是關於列表的第一個元素。 – Danilo

+0

我建議你進一步縮小問題的範圍。多久調用deleteRow()?你可以在那裏放置一些調試輸出。 – lex82

回答

0

我的建議是,函數deleteRow應該返回一個promise。函數sendToServer也應該返回一個你可以等待的承諾。它還應該從數組中調用deleteRow中收集承諾,並等待所有這些承諾完成。因此類似:

sendToServer : function(tmp) { 
    var promise = new Promise(); 

    var promiseArray = []; 
    for(x in tmp) 
    { 
    promiseArray.push(opSQL.deleteRow(tmp[x])); 
    } 

    Promise.all(promiseArray).then(function() { 
    // all successful 
    promise.resolve(); 
    }).catch(function() { 
    // something went wrong 
    promise.reject(); 
    }); 

    return promise; // <-- the caller should wait on this promise 
} 

根據您使用的承諾庫中提供的函數名稱進行調整。

希望這是有用的。