Question

We use a REST API and one of the features allows the user to do a mass edit of objects, which each requires a PUT request to edit said object. Right now we do

angular.foreach(objects, function(data) {
    restangular.one('user', user.id).one(object).put();
});
angular.updateInfo('user');

The problem here is that the updateInfo call happens async with the PUT calls so the new user info is not always complete/correct. Could it be possible to have something like.

var promise = restangular.one('user', user.id);
angular.foreach(objects, function(data) {
    promise.one(object).put();
});
promise.then(function (data) {
    angular.updateInfo('user');
});

Thanks :)

Was it helpful?

Solution

Yes, you can do this, but it's not quite as easy as how you've written it

I assume that each put will give you a promise (I have never used restangular). What you want to do is create a list of promises and then use $q.all.

NOTE be sure to inject $q into your controller/service.

// Initialise an array.
var promises = [];

angular.foreach(objects, function(data) {
    // Add the `put` to the array of promises we need to complete.
    promises.push(restangular.one('user', user.id).one(object).put());
});

// combine all the promises into one single one that resolves when
// they are all complete:
$q.all(promises)

// When all are complete:
.then( function(resultArray){

  // An array of results from the promises is passed
  var resultFromFirstPromise = resultArray[0];

  // Do whatever you want here.
  angular.updateInfo('user');

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top