我对 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/