1

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!

1 Answer 1

2

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 .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.