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)

functiongetKey (size) { 
  returnrandomBytesAsync(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 keyreturn result
}

Solution 2:

const crypto = require("crypto");

asyncfunctiongetRandomBytes(byteSize) {
  returnawaitnewPromise((resolve, reject) => {
    crypto.randomBytes(byteSize, (err, buffer) => {
      if (err) {
        reject(-1);
      }
      resolve(buffer);
    });
  });
}

asyncfunctiondoSomethingWithRandomBytes(byteSize) {
  if (!byteSize) return -1;
  const key = awaitgetRandomBytes(byteSize);
  //do something with key
}

doSomethingWithRandomBytes(16);

Solution 3:

const crypto = require('crypto');
    
    asyncfunctiongetKey(byteSize) {
        const buffer = awaitnewPromise((resolve, reject) => {
    crypto.randomBytes(byteSize, function(ex, buffer) {
      if (ex) {
        reject("error generating token");
      }
      resolve(buffer);
    });
    }
    
    asyncfunctiong() {
        let key = awaitgetKey(12);
        return key;
    }

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