Node.js module.exports一个带输入的函数
我有一个加密文件,在一些输入后添加一个加密的随机数:
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);
})
}
当我将其导出到另一个文件和console.log时,返回的值是未定义的
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
对于节点版本> 8,你可以使用没有promise链的简单async/await
。你必须使用utils.promisify
(在节点8中添加)将你的api包装在一个promise中,你的函数应该使用关键字async
.Errors可以使用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));