首页 > 解决方案 > 将异步函数直接导出为模块不会加载到其他模块中

问题描述

我一直在寻找这个问题,但找不到原因。我刚刚开始从事一个新项目,虽然我能够使用其中一种方式获得结果,但是为什么当我们直接导出它时它不起作用。

当我尝试像这样导出异步函数时,我收到一条错误消息,指出这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;

它说类型错误,我将其附加到问题中。我做错什么了吗?我怎样才能让功能运行?

错误图片:

在此处输入图像描述

标签: javascriptnode.jsexpressasync-await

解决方案


你的函数是异步的并不重要。

当您导出这样的函数时:

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 = () => {
    // ...
}

推荐阅读