Jacs Jacs - 3 years ago 322
CoffeeScript Question

Javascript return value from nested function prints undefined

Here i'm trying to return value from bcrypt.compare, nested inside a function.

I want to get the result value (true or false).

Im using coffeescript. Here is the code:

comparePasswordWithHash = (pass, hash) ->
return bcrypt.compare pass, hash, (err, result) ->
if err
throw err
return result

console.log comparePasswordWithHash "bacon", hashedPassword # Should print true/false

With this code, value printed is undefined.

Answer Source

bcrypt.compare() is asynchronous. This means that it is not returning anything, but instead calls the callback you pass to it. There is also a sync version of compare() --> bcrypt.compareSync().

My coffeescript is a little rusty, but I think you would end up with something like this using the promise:

comparePasswordWithHash = (pass, hash) -> bcrypt.compare pass, hash

comparePasswordWithHash "bacon", hashedPassword
.then (response) ->  console.log response
.catch (error) -> console.log error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download