Saturday, July 16, 2016

Broken Promises? Bluebird Solves It!

Broken promises. denodeify and Q's denodeify both doesn't work on MassiveJS:

let find = denodeify(db.notification.email.find)
let find = Q.denodeify(db.notification.email.find)

And even bluebird's promisify doesn't work:

let find = bluebird.promisify(db.notification.email.find)


All of them when this is performed:

find({locationId: 168}).then(result => {
}


Results to this:

TypeError: Cannot read property 'query' of undefined
    at Queryable.find (/Users/geek/WebstormProjects/personal/node_modules/massive/lib/queryable.js:108:12)


Those promisifier libraries might be having a hard time converting MassiveJS callback to promise as the target method(find) are dynamically generated.


And then I read bluebird's promisifyAll method. It can create a promise version of each methods in the object.

let email = bluebird.promisifyAll(db.notification.email);

With that, it will generate a promise version of all the methods found in db.notification.email object. The promise version of the method have the Async suffix on the method name.


An example use:

email.findAsync({locationId: 168}).then(result => 
});

And it works!


Then I found another approach that works in bluebird, it can also target specific method to promisify. You just have to pass the immediate object of the method you want to promisify on the second parameter.

let find = bluebird.promisify(db.notification.email.find, db.notification.email);

find({locationId: 168}).then(result => {

});


Happy Coding!

No comments:

Post a Comment