AngularJS $q.all update/notify not called why?

断了今生、忘了曾经 提交于 2019-12-11 12:09:42

问题


So I have a simple example of using $q.all to batch $resource calls, what I want to know is why is my update handler never called?

I would have thought it would be called after each promise is successfully completed?

Only the result handler is called. What am I doing wrong?

Here is the code snippet:

      var promises = [];
        angular.forEach($scope.mappedData, function(item) {
            var resource = new Resource(item);
            promises.push(resource.$save());
        });

        $q.all(promises).then(
            function(result) {
                console.log('result', result);

            },
            function(error) {
                console.log('error', error);

            },
            function(notify) {
                console.log('notify', notify);
            }
        );

回答1:


$q.all creates a new singular promise that once all the previous promises are complete will then continue on. If you want to do each one individually you'll have to reference them individually.




回答2:


I had the same problem, and I came with this solution. I've tried to arrange the code for your case.

var results = [], errors = [], d = $q.defer()
angular.forEach($scope.mappedData, function(item) {
    var resource = new Resource(item);
    resource.$save().promise
    .then(function (result) {
        results.push(result)
        if(results.length == $scope.mappedData.length)
            d.resolve(results) 
    }, function (err) {
        errors.push(err)
        results.push(null) // Very important =P
    }, function (notf) {
        d.notify(notf)
    })
})

d.promise.then(function (results) {
    console.log(results)
}, function (err) {
    console.error(err)
}, function (notf) {
    console.info(notf)
})

Let me know if it helps ;)



来源:https://stackoverflow.com/questions/28322912/angularjs-q-all-update-notify-not-called-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!