【问题标题】:Node.js argon2 Package Will Not Return StringNode.js argon2 包不会返回字符串
【发布时间】:2020-09-04 11:29:13
【问题描述】:

我正在编写一个需要密码哈希的网络应用程序。我正在使用来自 npm 的 argon2 包来实现这一点。

下面是我编写的一个函数,它返回一个字符串,例如$argon2i$v=19$m=4096,t=3,p=1$QC3esXU28vknfnOGCjIIaA$f/2PjTMgmqP1nJhK9xT0bThniCEk28vX2eY6NdqrLP8,但当值为console.log(ed)时,该函数返回Promise { <pending> }

代码是:

async function hashPassword(password) {
    try {
        const hash = await argon2.hash(password);
        return hash;
    } catch {
        console.log('Error');
    }
}
const hashedPassword = hashPassword('password');
console.log(hashedPassword);

所以,console.log() 的输出是 Promise { <pending> }

有人可以帮我解决这个问题吗?

非常感谢。

【问题讨论】:

    标签: node.js npm argon2-ffi


    【解决方案1】:

    调用hashPassword()时需要await

    async function hashPassword(password) {
        try {
            const hash = await argon2.hash(password);
            return hash;
        } catch {
            console.log('Error');
        }
    }
    const hashedPassword = await hashPassword('password');
    console.log(hashedPassword);
    

    【讨论】:

      【解决方案2】:

      您的代码不起作用,因为您试图在解决之前获取Promise 的值。要解决这个问题,只需等待 Promise 返回一个值。您可以通过更改代码以使用 then 函数 (MDN Docs link) 来做到这一点。

      async function hashPassword(password) {
          try {
              return await argon2.hash(password)
          } catch {
              console.log('Error');
          }
      }
      
      hashPassword('password').then((hashedPassword) => {
          console.log(hashedPassword);
      });
      

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 1970-01-01
        • 2014-02-14
        • 2010-11-11
        • 1970-01-01
        • 2014-03-04
        • 2014-02-09
        • 2011-11-22
        • 1970-01-01
        相关资源
        最近更新 更多