[英]Node.js module.exports a function with input
我有一個小的加密文件,它在一些輸入后添加了一個加密的隨機數:
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);
}
沒運氣。
提前致謝。
您可以使用承諾來處理異步功能
嘗試更改您的 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);
})
});
};
然后你可以使用promise鏈調用promise函數
let e = require("./encryption.js");
e(1, 2).then((res) => {
console.log(res);
}).catch((e) => console.log(e));
建議你閱讀Promise 文檔
對於節點版本 > 8,您可以使用簡單的async/await
而不使用承諾鏈。您必須使用utils.promisify
(在節點 8 中添加)將您的 api 包裝在承諾中,並且您的函數應使用關鍵字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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.