javascript - Angular js 在使用 foreach 完成多个 http 调用后回调

标签 javascript angularjs

我正在发送多个 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/

相关文章:

angularjs - 将数据从一个指令传递到另一个指令

javascript - 在 Angular/Ionic 应用程序中保持标题固定在滚动条上

javascript - Angular Tour 指令问题

javascript - 带有 NuGet 的 Visual Studio javaScript 默认目录

javascript - Facebook 如何禁用浏览器的集成开发人员工具?

javascript - 当 <a> 在另一页上单击并在另一页上打开特定选项卡时如何打开特定选项卡

css - 使用dasharray和dashoffset计算进度圈背后

javascript - 当从 Controller 调用 api 时,在回调中获取返回值(在 Angular Directive(指令)中)

javascript - 如何使用 Airbnb JavaScript 样式指南设置 Prettier

c# - IOAuthCredentials 哪个命名空间包含这个