hyades hyades - 4 months ago 33
Node.js Question

Bluebird Promises with Event Emitter

I am fairly new with using Bluebird promises. I was trying to use them over an emitter. However, I am stuck on how to handle errors.

I have a

object which is the emitter. Code is as below -

return new Promise((resolve, reject) => {

stream.on('data', onDocFunc);

stream.on('end', () => {
JSON.parse('*'); // how to catch errors that happen here??
var boundResolve = resolve.bind(this, {count: count});
if (count % bulkSize != 0) {
else {

stream.on('error', err => {


I want to know what is the recommended way to catch an error which occurs inside the callback of the
event handler? Right now if any error occurs, the NodeJS application crashes with
uncaughtException: Unexpected token *


Don't mix application logic into the promisification of the event emitter. Such code (that can throw etc) should always go in then callbacks. In your case:

var execute = Promise.promisify(bulk.execute);
return new Promise((resolve, reject) => {
    stream.on('data', onDocFunc); // not sure what this does
    stream.on('end', resolve);
    stream.on('error', reject);
}).then(() => {
    JSON.parse('*'); // exceptions that happen here are caught implicitly!
    var result = {count: count};
    if (count % bulkSize != 0) {
        return execute().catch(()=>{}).return(result);
    } else {
        return result;