這是我的工廠,它從API獲取數據並將每個數據存儲到SQLLite數據庫。在angularjs中解析多個承諾
team.factory('dataSync', function($q,$http,$timeout,$cordovaSQLite){
return {
getData:function(){
var q = $q.defer();
$http.get(api+'/sync/').then(function(response){
q.resolve(response);
},function(error){
q.reject();
})
return q.promise;
},
saveData:function(){
var q= $q.defer();
this.getData().then(function(result){
var data= result.data;
var sharing = data.sharing;
var help = data.help;
var message = data.message;
var questions = data.question;
var promises = [];
angular.forEach(sharing, function(value, index) {
console.log(value);
var sharingsql="INSERT INTO sharing (id,content_order,content ,last_modified)VALUES(?,?,?,?)";
$cordovaSQLite.execute(db,sharingsql,[value.id,value.content_order,value.content,value.last_modified]).then(function(result){
console.log(result.insertId);
//q.resolve(true);
},function(error){
console.log(error.message);
})
});
angular.forEach(help, function(value, index) {
console.log(value.message);
var helpsql="INSERT INTO help (id,message,message_position,last_modified)VALUES(?,?,?,?)";
$cordovaSQLite.execute(db,helpsql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
console.log(result.insertId);
},function(error){
console.log(error.message);
})
});
angular.forEach(message, function(value, index) {
var messagesql="INSERT INTO messages (id,message,message_position,last_modified_date)VALUES(?,?,?,?)";
$cordovaSQLite.execute(db,messagesql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
console.log(result.insertId);
},function(error){
console.log(error.message);
})
});
angular.forEach(questions, function(value, index) {
console.log(value.id+' '+index);
var questionsql="INSERT INTO questions (id,question_status,questions,question_order,last_modified)VALUES(?,?,?,?,?)";
$cordovaSQLite.execute(db,questionsql,[value.id,value.question_status,value.question,value.question_order,value.last_modified]).then(function(result){
console.log(result.insertId);
},function(error){
console.log(error.message);
})
});
$timeout(function(){
},2000).then(function(){
//q.resolve(true);
})
},function(error){
q.reject();
});
return q.promise;
}
}
});
致電$cordovaSQLite.execute
返回承諾。
我想在所有承諾解決後返回true
。我如何解決每個循環中解決的所有承諾?
當我搜索這個時,我發現$q.all
作爲答案。然後我讀了一些關於這個的教程,但不能在這裏實現。
避免[deferred antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi
[AngularJS可能重複 - 等待多個資源查詢完成](http://stackoverflow.com/questions/15299850/angularjs-wait-for-multiple-resource-queries-to-complete) –
是的,'$ q .all'就是答案。請告訴我們你是如何嘗試使用它的。 – Bergi