【发布时间】:2015-07-03 10:40:40
【问题描述】:
(这不是JavaScript closure inside loops – simple practical example的重复,因为你不能选择catch函数接受哪些参数)
我不熟悉 Node.js 的异步回调特性。我试图找出 for 循环中的哪个元素引发了异常。
当前代码总是返回数组中的最后一个元素,不管是哪个元素抛出了异常。
for (i = 0; i < output.length; i++) {
var entity = Structure.model(entity_type)[1].forge();
/* do some stuff here which I've taken out to simplify */
entity.save()
.then(function(entity) {
console.log('We have saved the entity');
console.log(entity);
returnObj.import_count++;
})
.catch(function(error) {
console.log('There was an error: ' + error);
console.log('value of entity: ', entity); /* THIS entity variable is wrong */
returnObj.error = true;
returnObj.error_count++;
returnObj.error_items.push(error);
})
.finally(function() {
returnObj.total_count++;
if (returnObj.total_count >= output.length) {
console.log('We have reached the end. Signing out');
console.log(returnObj);
return returnObj;
} else {
console.log('Finished processing ' + returnObj.total_count + ' of ' + output.length);
}
})
}
如何编写 Promise,让我可以访问引发异常的元素,以便将其存储在有问题的元素列表中?
【问题讨论】:
-
返回最后一个元素是什么意思?
-
我的意思是,在我遍历 30 个元素之后,它总是返回元素 30,而不是导致异常的元素(例如 15)。
-
如果您认为不是重复的,请参考infamous loop issue。这是完全相同的问题 - 您不必选择
catch或onclick或任何回调采用的参数。 -
非常感谢您指出这一点。恐怕我不熟悉“闭包”的词汇,也没有意识到这个问题不仅限于异步 try-catch 语句。因此,当我搜索该问题时,我没有找到您链接到的答案。有没有可能其他人会做同样的事情?
标签: javascript node.js exception callback promise