[英]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.