Search code examples
angularjsqueuerestangular

Post an array of objects with Restangular - AngularJS


I'm using Restangular to make my API call for a single object, like this:

$scope.box = { name : "box_a" , id : 1 };

Restangular.all('boxes/')
    .post($scope.box)
    .then(function(){
        ...
    });

But now, the user can select multiple boxes to add at once. So, I want to post multiple objects to my API, but I need to wait for each request until it's done, or my database will 'lock'...

My quick-add objects are the following:

$scope.boxes = [
    { name : "box_a" , id : 1 },
    { name : "box_b" , id : 2 },
    { name : "box_c" , id : 3 }
]

How can I create a promise chain by looping through my $scope.boxes? I can't quite figure out how to create an array of promises with Restangular...


Solution

  • I don't know much about restangular, but you could chain those requests with a reduce function like:

    $scope.boxes.reduce(function(promise, newBox){
        return promise.then(function(){
    
          return Restangular.all('boxes/')
                 .post(newBox)
                 .then(function(){
                     ...
                 });
        });
      }, $q.resolve());
    

    I've made a fiddle (wihout restangular, just a post call) and it seems to work.