javascript - Angularjs:$resource chaning 与 $http 调用

标签 javascript angularjs promise angular-resource angular-http

我如何比较这些不同调用的结果? url 和水果列表存储在不同的 json 文件中,在我将它们作为 promise 发送之前,我会比较它们。他们应该互相等待,并履行共同的 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]);
        }
      });
    });
  });

我知道这有点奇怪,但我必须以这种方式去做。

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

如有任何帮助,我们将不胜感激!

最佳答案

你使用 $q.all 得到一个 promise ,它的 .then 解包了它们:

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
});

$q.all 的指南说:

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

在 Bluebird 等其他 promise 库和 ES6 promise 中,该功能可能是 Promise.all,在原始 Q 中是 Q.all

关于javascript - Angularjs:$resource chaning 与 $http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23660973/

相关文章:

javascript - angularJS 我可以在指令中使用参数吗?

javascript - 用 Promises 返回的数据替换出现的文本

javascript - ExpressJS : Promises and Error Handling middleware

javascript - 在音位间隙中。是否有必要在所有html页面中包含cordova-2.0.0.js?

javascript - 有没有办法查看事件循环中的 promise 数量?

javascript - AngularJS 和 Web API 中请求的资源上不存在 'Access-Control-Allow-Origin' header

javascript - 带有 TypeScript 的 JQWidget

javascript - jQuery Deferred - 捕获与失败

javascript - 有没有办法在 Git 的不同分支上拥有不同的 JavaScript 库版本?

javascript - 解析文本区域以从内容返回 URL