如何将await与promisify一起使用crypto.randomBytes? [英] How to use await with promisify for crypto.randomBytes?

查看:67
本文介绍了如何将await与promisify一起使用crypto.randomBytes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数来使用crypto.randomBytes生成一个随机密钥,该函数需要一个回调.我更喜欢使用异步等待,所以我试图使用util.promisify来包装这样的随机字节:

I'm writing a function to generate a random key using crypto.randomBytes, which takes a callback. I'd prefer to use async await so I'm trying to use util.promisify to wraprandom bytes like this:

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 = genRandKey();
console.log('key: ', result);

但这会打印键:Promise {< pending>} 而不是打印已解析的值.我在这里做什么错了?

But this prints key: Promise { <pending> } instead of printing the resolved value. What am I doing wrong here?

推荐答案

所有 async 函数都返回一个诺言.因此,您的 genRandKey()函数也返回一个诺言.您必须对 genRandKey()的结果使用 await .then().仅仅因为您转换为Promise并使用了 await 并不意味着您可以直接从函数中返回值.这不是 async 函数中发生的事情. async 函数中的 return 值仅成为该函数返回的promise的解析值.同时,代码看起来就像您直接返回该值一样,而实际情况并非如此.

All async functions return a promise., So your genRandKey() function returns a promise too. You have to use await or .then() on the result from genRandKey(). Just because you converted to a promise and used await does not mean you can directly return the value from the function. That's not what is happening in an async function. The return value in an async function just becomes the resolved value of the promise that the function returns. While, the code looks like you are returning the value directly, that's not what is actually happening.

在Javascript/node.js中,没有办法获取异步检索的值并直接从函数返回它.必须通过promise,回调或事件将其传达回去.没有办法解决.

In Javascript/node.js, there is NO way to take an asynchronously retrieved value and return it directly from a function. It has to be communicated back via a promise or a callback or an event. There is no way around it.

现在,在这种特定情况下,有一个同步版本的 crypto.randomBytes(),您可以改用它.异步版本的存在是有原因的,因为 crypto.randomBytes()需要花费一些时间才能运行,如果您使用同步版本,它将在运行时阻止事件循环.取决于您正在做什么,这可能是问题也可能不是问题.异步版本的 crypto.randomBytes()在单独的线程中运行实际的加密操作(使用libuv线程池),并异步返回该值,从而不会阻塞事件循环.

Now, in this specific case, there IS a synchronous version of crypto.randomBytes() and you could use that instead. The asynchronous version exists for a reason because crypto.randomBytes() takes a little while to run and if you use the synchronous version, it will block the event loop while it is running. Depending upon exactly what you are doing, this may or may not be a problem . The asynchronous version of crypto.randomBytes() runs the actual crypto operations in a separate thread (using the libuv thread pool) and returns the value asynchronously so it doesn't block the event loop.

这篇关于如何将await与promisify一起使用crypto.randomBytes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆