Angular.forEach Nested Promises Resolution

I need to make sequential AJAX calls after retrieving a dataset. I have problems with nested promises.

Basically, I need to expand each object returned in my first collection with a property ActionItemsand set its value with a promise, and then solve every promise in the collection.

Any help would be greatly appreciated.

Factory

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

Current output undefined

+4
source share
2 answers

Well, it turns out that this method works, but the key to returning your data is returned ...

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

Thanks to everyone who helped.

+3
source

$http.get(...).then().

.then , " , 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.

+1

Source: https://habr.com/ru/post/1570171/


All Articles