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