2014-03-31 117 views
2

我们使用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'); 
}); 

谢谢:)

回答

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

});