NodeJS - 循环内的延迟函数

时间:2014-06-01 22:03:20

标签: 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);
        });
    }
});

编辑,我的真实代码与Benjamin的帮助(仍然无效):

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

1 个答案:

答案 0 :(得分:4)

您使用.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
});