简体   繁体   中英

NodeJS - Deferred function inside a loop

I have a conceptual problem with NodeJS... I need to call a deferred function within a loop and use the response for the next iteration. How can I do that without blocking? Here is what I did but of course, response.rev doesn't get updated for the next iteration:

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

Edit , my real code with Benjamin's help (still not working):

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

You use .then for that. .then is the asynchronous version of the semicolon:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM