0

I'm using a library providing a class whose constructor makes use of the Node.js callback pattern:

new FooBar({key: value}, function(err, data) {
  console.log(data);
});

I want to use a promise instead so that I can do something like this:

fooBarWrapper({key: value}).then(function(data) {
  console.log(data);
});

I know I can create a wrapper with Q.denodeify or call a function with Q.nfcall, but how does it work for constructors?

Michel Krämer
  • 14,197
  • 5
  • 32
  • 32

2 Answers2

1

I managed to solve it myself. You can use Q.defer to convert the callback to a promise:

var deferred = Q.defer();
new FooBar({key: value}, deferred.makeNodeResolver());
deferred.then(function(data) {
  console.log(data);
});

I'm leaving this answer here in the hope that it helps anybody else having the same problem.

Michel Krämer
  • 14,197
  • 5
  • 32
  • 32
1

Constructors shouldn't make asynchronous calls. This is not fun to do because the person making this library are performing async IO in constructors which is totally not cool of them :)

I suggest you wrap that function in a callback:

function fooBar(val, cb){
    new FooBar(val, cb);
}

Which would let you call Q.nfcall or Q.denodeify from your code. I believe this is better than creating an explicit deferred.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504