0

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

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

代码是:

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> }

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

非常感谢。

4

2 回答 2

1

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

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

hashPassword('password').then((hashedPassword) => {
    console.log(hashedPassword);
});
于 2019-12-09T07:15:50.793 回答
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);
于 2020-08-03T00:48:59.853 回答