我已经在angularjs中实现了$ q.all,但是我无法使代码正常工作。这是我的代码:
UploadService.uploadQuestion = function(questions){ var promises = []; for(var i = 0 ; i < questions.length ; i++){ var deffered = $q.defer(); var question = questions[i]; $http({ url : 'upload/question', method: 'POST', data : question }). success(function(data){ deffered.resolve(data); }). error(function(error){ deffered.reject(); }); promises.push(deffered.promise); } return $q.all(promises); }
这是我的控制器,它调用服务:
uploadService.uploadQuestion(questions).then(function(datas){ //the datas can not be retrieved although the server has responded }, function(errors){ //errors can not be retrieved also })
我认为在我的服务中设置$ q.all存在一些问题。
在javascript中 block-level scopes 不仅有 function-level scopes :
block-level scopes
function-level scopes
阅读有关javaScript作用域和提升的文章。
var deferred = $q.defer(); deferred.count = i; console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects // some code .success(function(data){ console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object deferred.resolve(data); })
var deferred= $q.defer();
for loop
closure scope
angular.forEach
这是一个演示插件:http ://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview
UploadService.uploadQuestion = function(questions){ var promises = []; angular.forEach(questions , function(question) { var promise = $http({ url : 'upload/question', method: 'POST', data : question }); promises.push(promise); }); return $q.all(promises); }
Array#map
这是一个演示插件:http ://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview
UploadService.uploadQuestion = function(questions){ var promises = questions.map(function(question) { return $http({ url : 'upload/question', method: 'POST', data : question }); }); return $q.all(promises); }