【问题标题】:Angularjs: $resource chaning with a $http callAngularjs:通过 $http 调用来改变 $resource
【发布时间】:2014-07-02 21:09:30
【问题描述】:

如何比较这些不同调用的结果? url 和水果列表存储在不同的 json 文件中,我会在将它们作为承诺发送之前对它们进行比较。他们应该彼此等待,并履行共同的承诺。

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

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript angularjs promise angular-resource angular-http


    【解决方案1】:

    你使用$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 的指南说:

    将多个 Promise 组合成一个 Promise,当所有输入 Promise 都已解析时,该 Promise 将被解析。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-07
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多