Node.js argon2 Package Will Not Return String

1.2k Views Asked by At

I am writing a web app that requires password hashing. I am using the argon2 package from npm to achieve this.

Below is a function that I have written that is ment to return a string such as $argon2i$v=19$m=4096,t=3,p=1$QC3esXU28vknfnOGCjIIaA$f/2PjTMgmqP1nJhK9xT0bThniCEk28vX2eY6NdqrLP8 but insted the function returns Promise { <pending> } when the value is console.log(ed).

The code is:

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

So, the output from the console.log() is Promise { <pending> }

Can someone please assist me in solving this problem?

Thank you very much.

2

There are 2 best solutions below

0
On BEST ANSWER

You need await when call hashPassword():

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);
0
On

Your code isn't working because you are attempting to get the value of a Promise before it resolved. To fix that, just wait for the Promise to return a value. You can do that by changing your code to use the then function (MDN Docs link).

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

hashPassword('password').then((hashedPassword) => {
    console.log(hashedPassword);
});