如何实现等待多个异步请求的承诺?

时间:2014-03-31 16:00:34

标签: angularjs restangular

我们使用REST API,其中一个功能允许用户对对象进行批量编辑,每个对象都需要PUT请求来编辑所述对象。现在我们做

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

这里的问题是updateInfo调用与PUT调用异步发生,因此新的用户信息并不总是完整/正确。是否有可能有类似的东西。

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

谢谢:)

1 个答案:

答案 0 :(得分:7)

是的,你可以这样做,但它并不像你写的那么容易

我假设每个put都会给你一个承诺(我从未使用过restangular)。你想要做的是创建一个承诺列表,然后使用$q.all

注意请务必将$q注入您的控制器/服务。

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

});
相关问题