如何在nodejs中使用crypto.randomBytes使用async/await?

Gar*_*ary 6 javascript node.js

const crypto = require('crypto');

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

async function g() {
    let key = await getKey(12);
    return key;
}

console.log(g());

console.log('hello - want this called after g() above');
Run Code Online (Sandbox Code Playgroud)

我已经这样做了一个小时,但我不明白如何确保我使用 async/await 获得密钥。无论我做什么,我都会收到一个待处理的 Promise。

我也尝试过这个:

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

getKey(12).then((result) => { console.log(result) })


console.log('hello');
Run Code Online (Sandbox Code Playgroud)

……没有用!其灵感来自: How to use wait with promisify for crypto.randomBytes?

谁能帮我这个?

我想做的就是获得 randomBytes 异步。使用 async./await 块,但在继续代码之前确保它履行承诺。

pet*_*teb 8

这是我对这个问题的评论的延伸

由于您没有承诺或将回调传递给crypto.randomBytes()它,因此它是同步的,因此您无法等待它。g()此外,您没有正确等待顶层返回的承诺。这就是为什么你总是在你的程序中看到待处理的 Promiseconsole.log()

您可以使用util.promisify()转换crypto.randomBytes()为承诺返回函数并等待它。在您的示例中不需要 the async/await,因为所做的只是用一个承诺包装一个承诺。

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))
Run Code Online (Sandbox Code Playgroud)

getKey()如果你想在样式函数中使用async/await它会像这样使用

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

  return result
}
Run Code Online (Sandbox Code Playgroud)