node.js promises:如何找出 .catch 语句中哪个迭代抛出异常?

node.js promises: how to find out which iteration threw the exception in a .catch statement?

(这不是 JavaScript closure inside loops – simple practical example 的副本,因为您无法选择 catch 函数采用哪些参数)

我不熟悉 Node.js 的异步回调特性。我试图找出 for 循环中的哪个元素引发了异常。

当前代码总是 returns 数组中的最后一个元素,无论哪个元素抛出异常。

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

如何以允许我访问抛出异常的元素的方式编写承诺,以便我可以将其存储在有问题的元素列表中?

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

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

.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 仅接收返回的函数作为参数)

如果实体是一个对象(只通过引用传递),你可以使用相同的基本原理,但你必须创建一个实体的副本,这会稍微复杂一些。在这种情况下,如果您使用原语 i 编写错误处理程序(作为一种原语类型,使用上述方法很容易捕获)或者如果您不在循环中重用实体变量,则可能会更容易。

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