javascript - 将异步函数直接导出为模块不会加载到其他模块中
问题描述
我一直在寻找这个问题,但找不到原因。我刚刚开始从事一个新项目,虽然我能够使用其中一种方式获得结果,但是为什么当我们直接导出它时它不起作用。
当我尝试像这样导出异步函数时,我收到一条错误消息,指出这hash
不是函数:
哈希.js
const bcrypt = require('bcrypt');
module.exports.hashing = async (password) => {
const salt = await bcrypt.genSalt(10);
const hashedResult = bcrypt.hashSync(password, salt);
console.log(hashedResult);
return hashedResult;
}
将散列模块导入注册模块:
const dbConnection = require('../db/db');
const errorCodes = require('../db/error.code.json');
const hash = require('../controllers/shared/hashing');
module.exports.register = async (req, res) => {
try {
const db = await dbConnection();
const {email, username } = req.body;
const password = await hash(req.body.password); --> it says hash is not a function
const user = new db({email: email, password: password, username: username});
user.save((err, result) => {
if (err) {
res.send(errorCodes[err.code])
return;
}
res.status(201).json(result)
});
} catch (error) {
console.log(error);
}
}
但是当我对 hashing.js 进行这些更改时,它可以工作:
const bcrypt = require('bcrypt');
const hashing = async (password) => {
const salt = await bcrypt.genSalt(10);
const hashedResult = bcrypt.hashSync(password, salt);
console.log(hashedResult);
return hashedResult;
}
module.exports = hashing;
它说类型错误,我将其附加到问题中。我做错什么了吗?我怎样才能让功能运行?
错误图片:
解决方案
你的函数是异步的并不重要。
当您导出这样的函数时:
module.exports.hashing = () => {
// ...
}
要正确使用它,您必须执行以下操作:
const {hashing} = require('../controllers/shared/hashing');
hashing();
// OR depending on your file context
const hash = require('../controllers/shared/hashing');
hash.hashing();
如果你想做:
const hash = require('../controllers/shared/hashing');
hash();
像这样导出你的函数:
module.exports = () => {
// ...
}
推荐阅读
- git - 使用 Jenkins 将一个 git 存储库镜像到另一个存储库
- arrays - 如何在bash for循环中读取数组的单个项目
- anylogic - 系统动力学中累积和的 AnyLogic 变量
- installation - install clFFT library on ubuntu for opencl programs
- shell - SFTP not printing error message or logging into a file
- atom-editor - 如何从 atom 命令脚本中选择 JSON 语法?
- c# - 如何使 IObservable
从控制台输入 - ios - Determine if a user has family sharing enabled
- visual-studio - Visual Studio: "Always show Error List if build finished with errors" does not w
- java - How can I implement a filewatcher in Java over a mapped network drive?