angular.forEach 解决嵌套承诺

angular.forEach Resolving Nested Promises

我必须在检索数据集合后进行顺序 AJAX 调用。我在解决嵌套承诺时遇到问题。

基本上,我需要使用属性 ActionItems 扩展第一个集合中返回的每个对象,并使用承诺设置它的值,然后解析集合中的每个承诺。

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

工厂

$http.get(urlBase + 'Project?$expand=Plant,CreatedBy,ModifiedBy,Plant/Contacts').then(function(success){
        var contents = {};
        contents = success.data.d.results;

        return contents;
    })
    .then(function(contents){ 
        var contentPromises = [];
        angular.forEach(contents, function(content) {
            contentPromises.push(
                $http.get(urlBase + "ActionItems?$filter=ProjectId eq " + content.Id ).then(function(success){
                    content['ActionItems'] = success.data.d.results;                         
                })
            );
        });
        return $q.all(contentPromises).then(function() {
            return contents;
        });
    });

当前输出未定义

您的问题出在 $http.get(...).then() 部分。

The documentation for .then 告诉我们 "This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback"。 所以 .then 返回的承诺与 $http.get 返回的不同。您有责任解决或拒绝它(通过退货)! .then 返回的承诺是推送到 contentPromises 的承诺。

因此你需要这样的东西:

angular.forEach(contents, function(content) {
    contentPromises.push(
        $http.get(urlBase + "ActionItems?$filter=ProjectId eq " + content.Id ).then(function(success){
            content['ActionItems'] = success.data.d.results;
            return success;                         
        })
    );
});

你最好也实施 errorCallback

事实证明此方法有效,但取回数据的关键是返回数据...

//Forgot the return below...
return $http.get(urlBase + 'Project?$expand=Plant,CreatedBy,ModifiedBy,Plant/Contacts').then(function(success){
    var contents = {};
    contents = success.data.d.results;

    return contents;
})
.then(function(contents){ 
    var contentPromises = [];
    angular.forEach(contents, function(content) {
        contentPromises.push(
            $http.get(urlBase + "ActionItems?$filter=ProjectId eq " + content.Id ).then(function(success){
                content['ActionItems'] = success.data.d.results;                         
            })
        );
    });
    return $q.all(contentPromises).then(function() {
        return contents;
    });
});

感谢所有帮助过的人。