我有一個承諾問題的foreach,承諾與angularjs
$scope.refreshProject = function() {
project.getAll().then(function(results) {
angular.forEach(results, function(project) {
project_path = project.path;
project_file = project.file;
project_id = project.id;
console.log(project);
console.log('http://' + project_path + '/' + project_file);
$http.get('http://' + project_path + '/' + project_file)
.then(function(res){
var project = new Project();
project.update(project_id, { 'content': res.data });
});
});
$scope.refresh();
});
};
我的$ http.get不工作,
的console.log(的 'http://' + project_path +'/'+ project_file);
回報
'http:///'
我的變量是空瓶。
project.model.js
Project.prototype.getAll = function() {
return ProjectService.getAll();
};
project.service.js
this.getAll = function (params) {
var projects = [];
return db.selectAll('projects').then(function(results) {
for(var i=0; i < results.rows.length; i++){
projects.push(results.rows.item(i));
}
return projects;
});
};
我怎麼能執行我的$ HTTP請求時,我從project.path的PARAMS和project.file可以嗎?
解決
project.getAll().then(function(results) {
angular.forEach(results, function(project) {
(function(project) {
var project_id = project.id;
if (project.path) {
var promise = $http.get(project.path + '/' + project.file)
.then(function(res){
var project = new Project();
console.log(res.data);
project.update(project_id, { 'content': res.data });
});
}
promises.push(promise);
})(project);
});
$q.all(promises).then(function() {
$scope.refresh();
console.log('refresh() ok');
});
});
使用'$ q.all'或'Promise.all' –
你是否檢查'的console.log(結果)'?這是對的嗎? – dfsq
在loop內部發送請求並不是個好主意。你的性能會很低,有時你的應用程序可能會崩潰,這就是爲什麼你需要在1個http請求中發送結果(作爲數組) –