gpt4 book ai didi

javascript - Node.js 模块。导出一个带有输入的函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:24 24 4
gpt4 key购买 nike

我有一个小的加密文件,在一些输入后添加了一个加密的随机数:

const crypto = require("crypto");

module.exports = function (x, y) {
crypto.randomBytes(5, async function(err, data) {
var addition = await data.toString("hex");
return (x + y + addition);
})
}

当我将它导出到另一个文件并控制台记录时,返回值是未定义的

const encryption = require('./encryption')
console.log(encryption("1", "2"));

我做错了什么?

我也试过

module.exports = function (x, y) {
var addition;
crypto.randomBytes(5, function(err, data) {
addition = data.toString("hex");
})
return (x + y + addition);
}

运气不好。

提前致谢。

最佳答案

您可以使用 promises 来处理异步函数

尝试更改您的 module.exports 以返回一个 promise 函数

const crypto = require("crypto");
module.exports = function (x, y) {
return new Promise(function (resolve, reject) {
var addition;
crypto.randomBytes(5, function (err, data) {
addition = data.toString("hex");
if (!addition) reject("Error occured");
resolve(x + y + addition);
})
});
};

然后您可以使用 promise 链调用 promise 函数

let e = require("./encryption.js");

e(1, 2).then((res) => {
console.log(res);
}).catch((e) => console.log(e));

推荐阅读Promise documentation

对于 Node 版本 > 8,您可以使用简单的 async/await 而无需 promise 链。您必须使用 utils.promisify(添加到 Node 8),您的函数应使用关键字 async。可以使用 try catch

处理错误
const util = require('util');
const crypto = require("crypto");
const rand = util.promisify(crypto.randomBytes);

async function getRand(x, y){
try{
let result = await rand(5);
console.log(x + y + result);
}
catch(ex){
console.log(ex);
}
}

console.log(getRand(2,3));

关于javascript - Node.js 模块。导出一个带有输入的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com