I'm new to Promises, and don't know how to resolve this problem: I'm doing an auth system, and my first call is to check email on database. If user exists, then check password against a bcrypted password... I'm using this lib for bcrypt: https://npmjs.org/package/bcrypt which is not promises compatible, so I'm using the "promisify" for the following signature: compare(password, crypted_password, callback).
So this is my code:
var compare = Promise.promisify(bcrypt.compare);
User.findByEmail(email)
.then(compare()) <--- here is the problem
This is my findByEmail method:
User.prototype.findByEmail = function(email) {
var resolver = Promise.pending();
knex('users')
.where({'email': email})
.select()
.then(function(user) {
if (_.isEmpty(user)) { resolver.reject('User not found'); }
resolver.fulfill(user);
});
return resolver.promise;
}
How to assign multiple values to the "compare" method in that case? Am I missing the point of promises?
To convert a callback into a promise, you need to return a promise. You run the code with the callback inside the promise. const readFilePromise = () => { return new Promise((resolve, reject) => { fs. readFile(filePath, options, (err, data) => { // ... }) }) }
The util. promisify() method basically takes a function as an input that follows the common Node. js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.
promisify. Returns a function that will wrap the given nodeFunction . Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function.
function promisify(f) { return function (... args) { // return a wrapper-function (*) return new Promise((resolve, reject) => { function callback(err, result) { // our custom callback for f (**) if (err) { reject(err); } else { resolve(result); } } args.
.then(compare()) <--- here is the problem
The then
method does expect a function which returns another promise [or a plain value], so you would need to pass compare
without calling it. If you need to specify the arguments, use a wrapper function expression:
User.findByEmail(email)
.then(function(user) {
return compare(/* magic */);
}).…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With