javascript - NodeJS - 循环内的延迟函数

标签 javascript node.js angularjs promise

我对 NodeJS 有一个概念性问题...我需要在循环中调用延迟函数并将响应用于下一次迭代。我怎样才能做到这一点而不阻塞?这是我所做的,但当然,response.rev 不会在下一次迭代中更新:

first.function().then(function(response) {
    for (var int = 0; int < $scope.files.length; int++) {
        call.function(response.rev).then(function (res) {
            response.rev = res.rev;
        }, function (reason) {
            console.log(reason);
        });
    }
});

编辑,在本杰明的帮助下我的真实代码(仍然无法工作):

pouchWrapper.updateClient(clientManager.clientCleaner($scope.client)).then(function(response) {
    if ($scope.files != null) {
        var p = $q.when();
        for (var int = 0; int < $scope.files.length; int++) {
            var doc = $scope.files[int].slice(0, $scope.files[int].size);
            p = p.then(function(formerRes){
                return pouchWrapper.uploadFiletoDoc($scope.client._id, $scope.contract.policy_number + '&' + $scope.damage.number + '-' + $scope.files[int].name, res.rev, doc, $scope.files[int].type).then(function (res) {
                    return res;
                }, function (reason) {
                    console.log(reason);
                });
            });
        }
        return p;
    }
});

最佳答案

您可以使用 .then 来实现这一点。 .then 是分号的异步版本:

first.function().then(function(response) {
   var p = $q.when(); // start with an empty promise
   for (var int = 0; int < $scope.files.length; int++) {
      p = p.then(function(formerValue){
              return call.function(formerValue).then(function (res) {
                  // use res here as the _current_ value
                  return res; // return it, so that the next iteration can use it;
              });
      });
   }
   return p; // this resolves with the _last_ value
});

关于javascript - NodeJS - 循环内的延迟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984966/

相关文章:

javascript - 图像附加不适用于 ng-repeat 中的指令

javascript - 在 Angular JS 中预填充 ng-repeat 内的下拉值

javascript - jQuery、JavaScript、在 Hover 上使用 3 个元素

Javascript有条件地调用链式方法

node.js - Express 和 Redis - 如果该用户存在 session ,则不允许访问

node.js - 在 Ubuntu 上将 NodeJS 作为服务运行

javascript - 尝试使用 HTML5/CSS3/JS 创建带有 z-index 的堆叠菜单

javascript - 无法调用 Angular 隔离范围指令上的方法

javascript - 使用 bodyParser 和 Router() 无法检索表单输入

javascript - AngularJS:为什么(显然)不需要为 ng-model 声明变量?