2

I was a huge promise chain, however I realized that one of the functions returns an object that has listeners and react to callbacks like

object.on('data', function(err, data) {
     //do something
});

object.on('exit', function(err, data) {
     //do something
});

I was wondering if there was a way to work this using promises and turn them into thenables. Is there no alternative to rewriting my entire promise chain to use callbacks?

Gakho
  • 603
  • 1
  • 9
  • 18
  • Suggested duplicate shows code converting callbacks and promises to each other. For node.js specific conversion check what promise library you use and adopt conversion code accordingly. – Alexei Levenkov Dec 17 '15 at 05:51

1 Answers1

5

Can't you wrap the object?

var promiseForObjectData = new Promise(function(resolve, reject) {

  // Note that you can't promisify data, because it gets called multiple times.
  object.on('data', function(err, data) {
    if (err) return reject(err);
    //do something
  });

  object.on('exit', function(err, data) {
    if (err) return reject(err);
    return resolve(...whatever...);
  });

});
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
robertklep
  • 198,204
  • 35
  • 394
  • 381