The async function genRandKey()
is being called synchronously, so it will return a Promise
. You can use the .then()
function to write to the console after the function has completed. You need to change the following code:
let result = genRandKey();
console.log('key: ', result);
to
genRandKey().then((result) => {
console.log('key: ', result);
});
However, this will cause the function to be called asynchronously while the rest of your code runs. A solution could be to wrap your whole program in a self-executing async function and use the await
keyword:
(async () => {
const crypto = require('crypto');
const util = require('util');
const randBytes = util.promisify(crypto.randomBytes);
async function genRandKey() {
bytes = await randBytes(48).catch((err) => {
console.log(err);
});
return bytes.toString('hex');
}
let result = await genRandKey();
console.log('key: ', result);
})();
Alternatively, you could just put the rest of the code in the .then()
function:
const crypto = require('crypto');
const util = require('util');
const randBytes = util.promisify(crypto.randomBytes);
async function genRandKey() {
bytes = await randBytes(48).catch((err) => {
console.log(err);
});
return bytes.toString('hex');
}
genRandKey().then((result) => {
console.log('key: ', result);
...rest of code...
});