[英]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 getKey(12);
return key;
}
console.log(g());
console.log('hello - want this called after g() above');
我已经处理了一个小时,但我不明白如何确保使用异步/等待获得密钥。 无论我做什么,我都会得到一个 Promise-pending。
我也试过这个:
async function getKey(byteSize) {
let key = await crypto.randomBytes(byteSize);
return key;
}
getKey(12).then((result) => { console.log(result) })
console.log('hello');
...无济于事:灵感来自: How to use await with promisify for crypto.randomBytes?
谁能帮我这个?
我想要做的就是让 randomBytes 异步。 使用 async./await 块,但在我继续编写代码之前确保它满足 promise。
这是我对这个问题的评论的延伸
由于您没有承诺或将回调传递给
crypto.randomBytes()
它是同步的,因此您不能等待它。 此外,您没有正确等待顶层g()
返回的 promise。 这就是为什么您总是在您的console.log()
中看到待处理的 Promise
您可以使用util.promisify()
将crypto.randomBytes()
转换为 promise 返回 function 并等待。 在您的示例中不需要async/await
,因为所做的只是用 promise 包装 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))
如果您想在async/await
样式 function 中使用getKey()
,它将像这样使用
async function doSomethingWithKey () {
let result
const key = await getKey(16)
// do something with key
return result
}
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);
如果不提供回调function,则同步生成随机字节并作为Buffer返回
// Synchronous
const {
randomBytes
} = await import('node:crypto');
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.