I'm trying to wrap my head around promises using the Bluebird library for Node.js.
Below is a simple example that doesn't work as I would expect.
var Promise = require("bluebird");
var myObj = {
add: function(op1, op2) {
return op1 + op2;
}
};
// Sync call to add method -> 7
console.log(myObj.add(3,4));
var myObjAsync = Promise.promisifyAll(myObj);
// Async call to promisified add method -> nothing written to console
myObjAsync.addAsync(2,3).then(function(data) {
console.log(data);
return data;
})
I'm either missing some (major) concept with promises or with Bluebird.
Thanks in advance for your help.
EDIT: Revised (and now working version) based on feedback from jfriend00.
var Promise = require("bluebird");
var myObj = {
add: function(op1, op2) {
return op1 + op2;
}
, add2: function(op1, op2, callback) {
callback(null, op1 + op2);
}
};
// Sync call to add method -> 7
console.log(myObj.add(3,4));
var myObjAsync = Promise.promisifyAll(myObj);
// Async call to promisified add method -> nothing written to console
myObjAsync.addAsync(2,3).then(function(data) {
console.log("%j", data);
return data;
})
// Async call to promisified add2 method -> 5
myObjAsync.add2Async(2,3).then(function(data) {
console.log("%j", data);
return data;
})
For
promisifyAll()
to work, the function has to be asynchronous and the last argument passed to the function has to be the completion callback and the completion callback has to have as its first argument, an error argument that is falsey when there's no error and the return value as the second argument (if there is a value).Your function doesn't meet any of those criteria.
Here's an excerpt from the Bluebird doc for
.promisifyAll()
:Please remember that
.promisifyAll()
can't make a synchronous operation into an async operation. What is does is take an asynchronous operation that conforms to a specific calling convention and wraps that into in a promise by hooking the callback and testing the callback's arguments to detect success or failure and to propagate the return value.If you're curious about how Bluebird does this, you can inspect their actual code here on Github, though it is not super easy to follow exactly what it does without some significant study.
Here's a bit simpler version of a promisify function to just see what it does (I'd recommend using Bluebird for all of it's other features rather than this).
Here's a working demo of this
promisify()
function: https://jsfiddle.net/jfriend00/m1265vos/