简体   繁体   English

嵌套函数的Javascript返回值打印未定义

[英]Javascript return value from nested function prints undefined

Here i'm trying to return value from bcrypt.compare, nested inside a function. 在这里,我试图从嵌套在函数内的bcrypt.compare返回值。

I want to get the result value (true or false). 我想获取结果值(对或错)。

Im using coffeescript. 我正在使用coffeescript。 Here is the code: 这是代码:

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

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

With this code, value printed is undefined. 使用此代码,打印的值是不确定的。

bcrypt.compare() is asynchronous. bcrypt.compare()是异步的。 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() . 还有一个compare() -> bcrypt.compareSync()的同步版本。

My coffeescript is a little rusty, but I think you would end up with something like this using the promise: 我的coffeescript有点生疏,但我认为您使用诺言最终会得到如下结果:

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

comparePasswordWithHash "bacon", hashedPassword
.then (response) ->  console.log response
.catch (error) -> console.log error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM