node.js承诺:如何找出哪个迭代抛出.catch语句中的exception?

(这不是JavaScript内部循环的重复- 简单实用的例子,因为你不能selectcatch函数采用哪些参数)

我不熟悉Node.js的asynchronouscallback性质 我试图找出for循环中的哪个元素抛出exception。

当前的代码总是返回数组中的最后一个元素,而不pipe哪个元素抛出exception。

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

我该如何编写承诺,让我可以访问抛出exception的元素,以便将其存储在有问题的元素列表中?

发生这种情况是因为传递给catch的匿名函数只能通过闭包访问entity

如果实体是原始types,则可以通过构造一个通过参数(其中entity的值将被复制构build时间)捕获该值的新函数轻松解决这个问题。

 .catch(function(entity){ return 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); }; }(entity)) 

(注意,我用()立即调用函数,所以catch只接收返回的函数作为参数)

如果实体是一个对象(只能通过引用传递),则可以使用相同的基本原则,但是必须创build此实体的副本,这会稍微复杂一些。 在这种情况下,如果使用原语i编写error handling程序(作为基本types,可以使用上述方法轻松捕获),或者在循环中不重复使用实体variables,则可能会更容易。

顺便说一句,你确定var entity = Structure.model(entity_type)[1].forge(); – >这里的1不应该是i吗?