Say, in the node.js module,, moduleA.jsI have the following object with a bunch of node-line asynchronous functions:
var init = function (data, callback) {
return callback(null, data.params );
};
var delay = function(data, callback) {
setTimeout(function(){
callback(null, data);
}, 1000*3);
}
var reverse = function(data, callback) {
var j,
d = {};
for(j in data) {
d[ data[j] ] = j;
}
callback(null, d);
}
module.exports = {
init: init,
delay: delay,
reverse: reverse
};
I consume moduleA.jsin main.jsand can successfully promisifyeach method individually, for example:
var Promise = require('bluebird'),
modA = require('./moduleA') );
var data = {
"a": "one",
"b": "two",
"c": "three",
"d": "four"
};
Promise.promisify(modA.init)(data)
.then( Promise.promisify(modA.delay) )
.then( Promise.promisify(modA.reverse) )
.then(function(data){
res.send(data);
}).catch(function(e){
next(e);
});
The above code works just fine, but more verbose than we would like.
My question is: how can I change my module to allow it Promise.promisifyAllto work correctly on the whole exported object? I want to avoid promisificationinside the module and allow others if necessary promisifyto consume it.
I tried unsuccessfully many options:
var Promise = require('bluebird'),
modA = require('./moduleA') ),
modAPromised = Promise.promisifyAll(modA);
var data = {
"a": "one",
"b": "two",
"c": "three",
"d": "four"
};
modAPromised.initAsync(data)
.then(modAPromised.delayAsync)
.then(modAPromised.reverseAsync)
.then(function(data){
res.send(data);
}).catch(function(e){
next(e);
});
When I do this, I get an error message Cannot call method 'delay' of undefined. Promise.promisifyAllAdds all functions Asyncas expected:
{
init: [Function],
delay: [Function],
reverse: [Function],
initAsync: {
[Function] __isPromisified__: true
},
delayAsync: {
[Function] __isPromisified__: true
},
reverseAsync: {
[Function] __isPromisified__: true
}
}
, - . -, delayAsync this.delay, this undefined.
, , Promise.promisifyAll ?
.