【问题标题】:Difference between hash() and hashSync() functions of BCrypt package of NodeJsNodeJs的BCrypt包hash()和hashSync()函数的区别
【发布时间】:2021-04-06 22:47:41
【问题描述】:
const bcrypt = require('bcrypt')

const hash = bcrypt.hash(<myPassword>, 12)

const hashSync = bcrypt.hashSync(<myPasword>, 12)

它们可能在哪些方面有所不同,它们可以互换使用吗? (非常欢迎和非常感谢详细的解释!)

【问题讨论】:

  • 为了快速理解,我记录了值“myPassword”的“hash”和“hashSync”的值:hash: Promise { &lt;pending&gt; }hashSync: $2b$12$xEpu8E8s0FGIC2wgYbacSO.KoMBQSEoOoobHxv3uWU.h/amo99Wg6
  • 这正是它的作用。非同步版本返回一个承诺而不是直接值。
  • 这能回答你的问题吗? Node.js sync vs. async

标签: javascript node.js passwords bcrypt password-hash


【解决方案1】:

bcrypt.hash 将回调作为其第三个参数,当哈希完成时将调用该回调。 bcrypt.hashSync 运行哈希,等待它完成并返回哈希值。

换句话说,“hash”是异步的,而 hashSync 是同步的。

【讨论】:

    【解决方案2】:

    你是说

    const bcrypt = require('bcrypt')
    
    const hash = bcrypt.hash(<myPassword>, 12) // this returns a promise 
    
    const hashSync = bcrypt.hashSync(<myPasword>, 12) //this on is sync so it stops every line of code after untill it's executed
    

    阅读this文章了解同步和异步的区别

    【讨论】:

      【解决方案3】:

      hashSync 用于为给定字符串同步生成哈希。它返回哈希字符串

      hash 用于为给定字符串异步生成哈希。它返回承诺是回调已提交,您需要解决承诺。

      参考https://www.npmjs.com/package/bcryptjs#hashsyncs-salt

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-20
        • 1970-01-01
        • 2015-11-08
        • 2011-05-16
        • 2015-10-31
        • 1970-01-01
        • 2015-05-08
        • 2012-12-21
        相关资源
        最近更新 更多