hyades hyades - 1 year ago 95
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 *

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download