How do I make multiple HTTP requests in my case

I am trying to bind a promise to an Angular $ resource.

I have the following factory:

angular.module('myApp').factory('Product', ['$resource', function ($resource) {
    return $resource(
        '/api/product/:name',
        { name: '@name' },
        { 'getSub': {
                url: '/api/product/getSub/:name',
                method: 'GET'}
         }
    );
}]);

      

I am making multiple requests using my product factory as such:

Product.query({'name': name}, function(product) {
     Product.getSub({'name': product.name}, function(subItem) {
         Product.getSub({'name':subItem.name}, function(childItem) {
             //do stuff with child item
         })
     })
})

      

Is there a better way to do this? I feel that nesting all of these calls is not best practice.

+3


source to share


4 answers


You can combine promises together!



Product.query({'name': name}).$promise
.then(function(product){
  return Product.getSub({'name': product.name}).$promise;
})
.then(function(subItem){
  return Product.getSub({'name': subItem.name}).$promise;
})
.then(function(item){
  // etc
})

      

+2


source


you can use waterfall async library or implement it yourself.
here's a sample code for your case.



async.waterfall([
    function(callback) {
        Product.query({'name': name}, function(product) {
            callback(null, product);
        })
    },
    function(product, callback) {
        Product.getSub({'name': product.name}, function(subItem) {
            callback(null, product, subItem);
        })
    },
    function(product, subItem, callback) {
        Product.getSub({'name':subItem.name}, function(childItem) {
            var result = {};
            result.childItem = childItem;
            result.subItem = subItem;
            result.product = product;

            callback(null, result);
        })
    }
], function (err, result) {
    //do stuff with result
});

      

+1


source


A helpful solution might be to use the $ q library

https://docs.angularjs.org/api/ng/service/ $ q

You can use the $ q.all () method to send a lot of requests and control only one then () callback or make $ q.defer () and allow por to reject your oun promises.

I am currently answering this question from a mobile device and I am unable to make an example. Sorry about that. If when I get home this train error still tries to help

0


source


If you want the queries to be executed one by one (as in your example), you can make a recursive function like this:

in this example, I want to upload multiple images (call http route):

$scope.uploadImageLayout = function (currentIndex, numberOfItems) {
        if (currentIndex === numberOfItems) {
            // in here you could do some last code after everything is done
        } else {
            Upload.upload({
                url: 'localhost:3000/ficheiros',
                file: $scope.imagesToUpload[$scope.auxIndex].file
            }).success(function (data, status, headers, config) {
                if ($scope.auxIndex < numberOfItems) {
                    $scope.uploadImageLayout(currentIndex + 1, numberOfItems);
                }
            });
        }
    };

      

and the first time you call this simply:

$scope.uploadImageLayout(0, $scope.imagesToUpload.length);

      

in your case it is the same, but instead of requesting Upload.upload you should have your request and catch the callback function (s).

0


source







All Articles