Angular - 多个承诺包含在一个承诺中

Angular - multiple promises wrapped in one promise

我有几个服务 return 相同类型的对象只是通过对象上的标志不同类型。这些服务具有 return 承诺的功能。

服务 1 - getPlaces:

this.getPlaces = function () {
            return $http.get('http://somewhere.com').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

服务 2 - getPlaces:

this.getPlaces = function () {
            return $http.get('http://somewhere.com/').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

我还有一个调用这两个服务的包装器服务,我不希望服务包装器中的函数 return 组合结果,直到两个承诺都完全执行并且 returned 结果(或 null)。我目前正在按照以下方式进行操作:

    this.getCombinedResults = function () {
        var combined= [];

        var apiCalls = [service1.getPlaces(), service2.getPlaces()];

        $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
        });            
        return combined;
    };

这是将多个承诺包装在一个承诺中的正确方法吗?如果不是应该改变什么。我认为它无法正常工作,尤其是在我的包装器服务中。调用包装器服务函数时,它 return 为 null。

我将对此进行更多研究,但如果我能提前了解我所写的内容是否正确,那就太好了。谢谢

由于 getCombinedResults 正在调用基于承诺的服务,因此该服务也应该 return 承诺,否则组合将始终为空。

随便做

 return $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
            return combined;
        }); 

因为then也是return一个承诺,这段代码将return一个承诺返回给调用者。

解析后的值为 combined

同样在调用代码中,您需要使用 then.

使用基于承诺的响应解析