猿问

AngularJS $ q.all

我已经在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存在一些问题。


qq_笑_17
浏览 634回答 3
3回答

不负相思意

问题似乎是您要添加deffered.promisewhen deffered本身就是您应该添加的承诺:尝试更改为promises.push(deffered);,这样就不会将未包装的Promise添加到数组中。&nbsp;UploadService.uploadQuestion = function(questions){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var promises = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0 ; i < questions.length ; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var deffered&nbsp; = $q.defer();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var question&nbsp; = questions[i];&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $http({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url&nbsp; &nbsp;: 'upload/question',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data&nbsp; : question&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success(function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deffered.resolve(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error(function(error){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deffered.reject();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; promises.push(deffered);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $q.all(promises);&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答