Scholle Scholle - 4 months ago 6
Node.js Question

How to make thrown errors visible outside of a Promise?

I am using csv-parse for stream parsing. For each record, I need to call some function

mapper.process()
. Since the latter function returns a promise, a wrapped it with
co
and prefixed
yield
.

parser.on('readable', function() {
var record;
while (record = parser.read()) {
return co(function*() {
yield mapper.process(record);
});
}
});


Without the addition (removing lines 4, 6 and
yield
), everything works fine. However, using the parser as shown above, thrown errors are swallowed.

How to fix this?

Answer

The problem here is that any thrown error will disappear because there is no catch handler after the co function.

But more importantly, the return statement inside the while loop will cause the whole function to return, so if you have multiple records in the buffer, you won't reach them.

You can write the following code to make it work:

parser.on('readable', function() {
  return co(function* () {
    var record;

    while (record = parser.read()) {
      const result = yield mapper.process(record);

      // do something with the result..
      console.log('result is ', result);
    }
  })
  .catch((err) => console.error(err));
});

BUT, please be aware that because you're dealing with asynchronous code inside the "readable" callback, you'll cause the function to return immediately. This behaviour will cause the "finish" event to be called by the parser at the end of the stream and probably before you've actually finished processing the data.