javascript - 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);
}
没运气。
提前致谢。
解决方案
你可以使用 Promise 来处理异步函数
尝试更改您的 module.exports 以返回一个承诺函数
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);
})
});
};
然后,您可以使用承诺链调用承诺函数
let e = require("./encryption.js");
e(1, 2).then((res) => {
console.log(res);
}).catch((e) => console.log(e));
建议你阅读Promise 文档
对于节点版本> 8,您可以使用没有承诺链的简单。您必须使用(在节点8中添加)async/await
将您的api包装在承诺中,并且您的函数应该使用关键字。可以使用处理错误utils.promisify
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));
推荐阅读
- typescript - 为什么我有这个错误 «Cannot read property 'authService' of undefined»
- javascript - !+ 在 Javascript 中是什么意思?
- prolog - 从 Prolog 的知识库中检索一个元素
- html - 边缘浏览器问题:宽度:在 chrome 中正常工作时不遵守 fit-content
- java - 监听 Redisson Object Holder (RBucket) 中对象的更改?
- excel - VBA:运行时错误 91 - 修复一行的问题
- airflow - 是否可以使用 BigqueryOperator 一次调用将数据结果存储到多个分区中?
- javascript - 如何将动态数字放入chart.js 图表中?
- flutter - 设计 Flutter 项目时图标不可见
- c++ - 假设的不完整类型错误:对象与指针