Skip to content Skip to sidebar Skip to footer

How To Use Async/await Using Crypto.randomBytes In Nodejs?

const crypto = require('crypto'); async function getKey(byteSize) { let key = await crypto.randomBytes(byteSize); return key; } async function g() { let key = await g

Solution 1:

This is an extension of my comment on the question

Since you're not promisify'ing or passing a callback to crypto.randomBytes() it is synchronous so you can't await it. Additionally, you're not properly awaiting the promise returned by g() at the top level. That is why you always see the pending Promise in your console.log()

You can use util.promisify() to convert crypto.randomBytes() into a promise returning function and await that. There is no need for the async/await in your example because all that is doing is wrapping a promise with a promise.

const { promisify } = require('util')
const randomBytesAsync = promisify(require('crypto').randomBytes)

function getKey (size) { 
  return randomBytesAsync(size)
}

// This will print the Buffer returned from crypto.randomBytes()
getKey(16)
  .then(key => console.log(key))

If you want to use getKey() within an async/await style function it would be used like so

async function doSomethingWithKey () {
  let result
  const key = await getKey(16)
   
  // do something with key

  return result
}

Solution 2:

const crypto = require("crypto");

async function getRandomBytes(byteSize) {
  return await new Promise((resolve, reject) => {
    crypto.randomBytes(byteSize, (err, buffer) => {
      if (err) {
        reject(-1);
      }
      resolve(buffer);
    });
  });
}

async function doSomethingWithRandomBytes(byteSize) {
  if (!byteSize) return -1;
  const key = await getRandomBytes(byteSize);
  //do something with key
}

doSomethingWithRandomBytes(16);

Solution 3:

  const crypto = require('crypto');
    
    async function getKey(byteSize) {
        const buffer = await new Promise((resolve, reject) => {
    crypto.randomBytes(byteSize, function(ex, buffer) {
      if (ex) {
        reject("error generating token");
      }
      resolve(buffer);
    });
    }
    
    async function g() {
        let key = await getKey(12);
        return key;
    }

Post a Comment for "How To Use Async/await Using Crypto.randomBytes In Nodejs?"