我如何比较这些不同调用的结果? 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/