$q.all and creation of a new object not working in the view

I'm having difficulty with $q.all not resolving in AngularJS. I may not be describing things correctly, but this is at least the scenario.

The Service

app.factory('myService', function($http){
    return {
        get: function () {
            return $http.get('http://localhost:8001/');
        }
    };
});

In the Controller

angular.forEach(array, function(item){
    promises.push({foo:myService.get(), bar: item});
});
$q.all(promises).then(function(results){
    $log.info(results);
    $scope.results = results;
});

In the view, anything taking values from bar displays correctly. Anything, however, taking its values from foo is blank. In the console bar is an inspectable object as you'd expect. But foo is still a promise. It has all the methods a promise would, but no data associated.

So, somehow, $q.all isn't resolved by the time the results are applied to the $scope. And why, I'm not sure.

I'll note that I've based what I'm doing above somewhat on what's here: angular.forEach and objects

Answers


$q.all is expecting an array of promises. try something like this:

angular.forEach(array, function(item){
    var foo = myService.get();
    var bar = myOtherService.get();
    promises.push(foo); 
    promises.push(bar);  
});

$q.all(promises).then(function(results){
    $log.info(foo);
    $log.info(bar); 
});

UPDATE

if you need you could nest multiple $q.all

angular.forEach(array, function(item){

    var deferred = $q.defer();

    $q.all([myService.get(), myOtherService.get()]).then(function(results){
      deferred.resolve({foo:results[0], bar: results[1]});
    });  

    promises.push(deferred.promise);

});

$q.all(promises).then(function(results){
    $log.info(results);
});

Can you make a plnkr? Also your array of "promises" aren't promises but a custom object where one property is the promise and the other is something else. If you want to make a promise hash it should look like this:

var promises = {};
angular.forEach(array, function(item){
    promises[item.foo] = item.promise;
});

$q.all(promises).then(...

Need Your Help

How does one preserve scope with nested directives?

javascript angularjs scope nested transclusion

My goal is to create a flexible set of directives for reusable and lightweight UI elements. Each has an isolated scope, and many of them transclude content. I want each directive to be a black box ...

Cannot convert JSONArray to JSONObject using Volley

android web-services android-volley android-json

I'm trying to use Volley for consuming a web service. This is my logcat output: