(this is not a duplicate of JavaScript closure inside loops – simple practical example because you can't choose which parameters the catch function takes)
I'm new to the asynchronous callback nature of Node.js. I'm trying to find out which element in a for loop threw an exception.
The current code always returns the last element in the array, regardless of which element threw the 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);
            }
        })
}
How do I write promises in a way that gives me access to the element that threw the exception so I can store it in a list of problematic elements?
 
     
    