我正在发送多个 HTTP 调用来更新 foreach 循环内的项目,并且在所有请求完成后需要回调。我发现this但没有帮助。
我的代码:
$q.all(_($scope.students.items).each(function(item) {
$scope.student.update(); //this is an http call
})).then(function() {
// I need a callback need here
alert("complete"); //should be shown after all students get updated but it is
// called before all network calls got complete
});
这是通用更新函数
self.update = function(item, callback) {
that.post(item, self.getUrl("update") , function(err, data) {
if (self.formatter) {
data = self.formatter(data);
}
callback(err, data);
});
};
有什么建议吗?
最佳答案
您在 update()
函数中错过了 return
关键字,因为它必须返回一个 Promise(当然,还有 that.post()
函数也必须返回一个 promise ):
self.update = function(item, callback) {
return that.post(item, self.getUrl("update") , function(err, data) {
if (self.formatter) {
data = self.formatter(data);
}
callback(err, data);
});
};
那么这应该可以工作:
var promises = [];
_($scope.students.items).each(function(item) {
promises.push($scope.student.update());
})
$q.all(promises).then(function() {
alert("complete");
});
关于javascript - Angular js 在使用 foreach 完成多个 http 调用后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38352371/