Pergunta

How could I compare the result of these different calls? The url, and the fruit list stored in a different json file, and I would compare them before I send them as a promise. They should wait each other, and fulfilled in a common promise.

angular.module('myApp', ['ngResource'])
  .controller('MainCtrl', function($scope, $http, $resource) {
    var list = {};
    $http.get('images.json').then(function(response) {
      response.data.objects.forEach(function(images) {
        list[images.id] = images.url;
      });
    });
    $resource('fruits.json').get().$promise.then(function(response) {
      var list = {
        1: 'badUrlExampleForApple',
        2: 'badUrlExampleForOrange',
        3: 'badUrlExampleForPineapple'
      }
      response.objects.forEach(function(product) {
        if (list[product.id]) {
          console.log(product.name + ': ' + list[product.id]);
        }
      });
    });
  });

I know it's a little bit feird, but I have to do it in this manner.

Plunker example: http://plnkr.co/edit/ICwvYI?p=preview

Any help would be greatly appreciated!

Foi útil?

Solução

You use $q.all to get a promise whose .then unwraps both of them:

var images = $http.get('images.json');
var fruits = $resource('fruits.json').get().$promise;

$q.all([images,fruits]).then(function(results){
    var images = results[0];
    var fruits = results[1];
    // access to both here, you can compare anything you want
});

The guide for $q.all says:

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

In other promise libraries like Bluebird and in ES6 promises, thatr functionality would probably be Promise.all, in the original Q it's Q.all .

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top