为了账号安全,请及时绑定邮箱和手机立即绑定

Node.js模块。使用输入导出函数

Node.js模块。使用输入导出函数

米脂 2021-04-23 12:17:04
我有一个小的加密文件,在一些输入之后添加了一个加密的随机数: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);}没有运气。提前致谢。
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

您可以使用Promise处理异步功能


尝试更改您的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文档


对于大于8的节点版本,您可以使用简单的async/await无承诺链。您必须将api包装在一个Promise中utils.promisify(在节点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));


查看完整回答
反对 回复 2021-04-29
  • 1 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信