Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird promisify multiple arguments

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?

like image 850
rizidoro Avatar asked Jan 21 '14 23:01

rizidoro


People also ask

How do you Promisify a callback function?

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) => { // ... }) }) }

What is the purpose of the util Promisify () function?

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.

What does promise Promisify do?

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.

How do you Promisify a function in Javascript?

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.


1 Answers

.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 */);
    }).…
like image 154
Bergi Avatar answered Sep 18 '22 16:09

Bergi