Sunday, 14 October 2018

try/catch block not working within promise chain in forEachSeries loop!

For some reason my try/catch blocks are not catching an error when they are in an "async.forEachSeries" loop, after a promise. I was wondering if somebody could help me determine what is happening here. I'm pretty sure there is something fundamental that I am missing here.I am getting the error "TypeError: Cannot read property 'field' of undefined", but this is not being caught.I cut down the code section that is producing the error and produced the following code that replicated the error. This is actually a followup to the question I posted hereThis code simply creates an object with two methods. One method returns a promise that returns undefined. The other method has a loop that iterates through an array. Within this loop, the first method is called. The function then attempts to access a property of the array, which should throw and error that should be caught by the try block. The problem is that the try block does not throw the error, and the catch block is never reached.var async = require("async"); class some_object { constructor() { } another_method_with_promise(){ return new Promise((fulfill, reject) => { fulfill(undefined); }); } some_method(instruction){ return new Promise((fulfill, reject) => { var some_array = [1,2,3]; async.forEachSeries(some_array, (array_cell, callback_func) => { try { //This does not throw an error this.another_method_with_promise().then( (data) => { if ((data["field"].indexOf("somestring") !== -1)){//should throw an error!! callback_func(); } } ) } catch (err) { //error should be caught here but is not console.log("catch block, but never reached!!"); callback_func(err); } }, () => { if (err) { reject(err); } if (!err){ fulfill() } } ); }); } } var foo = new some_object(); foo.some_method();

Submitted October 14, 2018 at 09:31PM by thenewstampede

No comments:

Post a Comment