Angularjs $q.all
我已经实现$ q.all在angularjs,但我不能让代码工作。这里是我的代码:
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中没有块级作用域只有功能级作用域:
阅读这篇文章关于javaScript Scoping and Hoisting。 看看我如何调试您的代码: 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 --< only the last deferred object deferred.resolve(data); }) >当你写var deferred = $ q.defer();在for循环中,它被提升到函数的顶部,这意味着javascript在for循环之外的函数范围上声明此变量。 有angular.forEach的解决方案: 这是一个演示plunker:http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview UploadService.uploadQuestion = function(questions){ var promises = []; angular.forEach(questions,function(question) { var promise = $http({ url : 'upload/question',data : question }); promises.push(promise); }); return $q.all(promises); } 我最喜欢的方法是使用Array#map: 这是一个演示plunker:http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview UploadService.uploadQuestion = function(questions){ var promises = questions.map(function(question) { return $http({ url : 'upload/question',data : question }); }); return $q.all(promises); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |