Suppose I created or have a node.js library lib.js
export class C {
constructor(value, callback) {
callback(false, `Hello ${value}`);
}
task(value, callback) {
callback(false, "returned " + value);
}
}
The important part is that the classes' constructor needs to accept a callback as it does database connections and file I/O. If I now import and use the library callback-style, everything is fine (see c1
below).
I would really like to promisify the library where I use it to make object construction more convenient (in reality it's a whole bunch of classes and methods).
However, I can't find a way to new
the class properly in a promise-safe nicely.
import Promise from 'bluebird';
import * as lib from './lib';
Promise.promisifyAll(lib);
// old style -- works as expected
const c1 = new lib.C("c1", (e, v) => {
console.log(c1, e, v);
});
// assuming c1 got initialized, .task() also works
c1.task("t1", console.log);
c1.taskAsync("t2").then(() => console.log("also works"));
// But how to do this properly with promises?
const c2 = new lib.C("c2"); c2.then(console.log); // clearly doesn't work, lack of callback
const c3 = new lib.CAsync("c3"); c3.then(console.log); // "cannot read property apply of undefined"
const c4 = ???
How would I do this best? Changing library signature isn't a good option, creating factory methods also seems to be ugly.