1

I'm trying to make crypto.randomBytes and crypto.createHash use async/await. So I tried the following:

The original and working code:

userSchema.methods.createPasswordResetToken = function() {
    const resetToken = crypto.randomBytes(32).toString('hex');

    this.password_reset_token = crypto.createHash('sha256').update(resetToken).digest('hex');

    this.password_reset_expires = Date.now() + (10*60*1000);

    console.log({resetToken}, this.password_reset_token);

    return resetToken;
};

So, I imported promisify and tried this:

userSchema.methods.createPasswordResetToken = async function() {
    const resetToken = promisify(crypto.randomBytes(32)).toString('hex');

    this.password_reset_token = promisify(crypto.createHash('sha256').update(resetToken).digest('hex'));

    this.password_reset_expires = Date.now() + (10*60*1000);

    console.log({resetToken}, this.password_reset_token);

    return resetToken;
};

But that resulted in this error:

UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function. Received an instance of Buffer

So I tried to use this solution https://stackoverflow.com/a/63125950/10033434, but I received this:

{ resetToken: '[object Promise]' }

Does anyone has a working solution? And another question, should I leave it as a synchronous function? And if I did, will the server suffer from a performance 'hit'?

Thanks in advance...

user10033434
  • 402
  • 5
  • 19

1 Answers1

0
  1. util.promisify needs a reference to a function, not a result of a function call.
  2. crypto.createHash() seems to not have an asynchronous variant, so it cannot be promisisfied.

This seems working:

const randomBytes = util.promisify(crypto.randomBytes);

userSchema.methods.createPasswordResetToken = async function() {
    const resetToken = (await randomBytes(32)).toString('hex');

    this.password_reset_token = crypto.createHash('sha256').update(resetToken).digest('hex');

    this.password_reset_expires = Date.now() + (10*60*1000);

    console.log({resetToken}, this.password_reset_token);

    return resetToken;
};
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26