Promisifying a callback
suggest changeCallback-based:
db.notification.email.find({subject: 'promisify callback'}, (error, result) => {
if (error) {
console.log(error);
}
// normal code here
});
Node's util.promisify wraps one error-first function. The samples below use Bluebird instead. promisifyAll adds a promise version of each method on the object, with Async appended to the name:
let email = bluebird.promisifyAll(db.notification.email);
email.findAsync({subject: 'promisify callback'}).then(result => {
// normal code here
})
.catch(console.error);
To wrap one method, use bluebird.promisify:
let find = bluebird.promisify(db.notification.email.find);
find({locationId: 168}).then(result => {
// normal code here
}).catch(console.error);
Some libraries (for example MassiveJS) cannot be promisified unless the method's owner object is passed as context:
let find = bluebird.promisify(db.notification.email.find, { context: db.notification.email });
find({locationId: 168}).then(result => {
// normal code here
}).catch(console.error);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents