【问题标题】:module.exports function is not defined after require from another filemodule.exports 函数未在另一个文件的 require 后定义
【发布时间】:2019-09-29 01:05:09
【问题描述】:

大家好,我从 nodejs 开始,我想我理解 module.exports 是如何工作的,但是当在 index.js 启动文件中要求并使用它之后在另一个文件中使用相同的函数时,我首先得到的是不是一个函数。我看到很少有类似的答案,但代码更复杂,我没有明白这就是为什么我在这里这么简单地问它的原因。让我更详细地解释一下,如果太基本,请见谅。

我运行 npm start 并从 index.js 文件开始

索引.js

const { first } = require("./first");

first();

First.js

const { second } = require("./second");

function first(){
    
    return second();
}

module.exports = {
    first
}

Second.js

const { first } = require("./first");

function second(){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>resolve(), 1500)
    })
    .then(()=> {
        first()
    })
    .catch(err => {
        // Here's the first is not a function
        console.log("Error here!!: ", err)
    })
}

module.exports = {
    second
}

在 second.js 文件的 catch 中抛出错误。上面写着:Error here!!: TypeError: first is not a function

【问题讨论】:

  • 究竟是什么错误,它是在哪里抛出的?
  • 欢迎亚历克斯!了解您遇到的错误会很有帮助。您能否将错误作为问题的一部分发布,以便我们知道确切的错误以及引发错误的位置。信息越多越好。
  • 第二个.js文件的catch中抛出错误。它说:此处出错!:TypeError:首先不是函数
  • 你为什么要做循环引用?
  • 因为我想再次执行第一个函数,直到基于 second.js 文件的某个条件

标签: javascript node.js


【解决方案1】:

这对我有用,你需要在 second.js 中添加另一个匿名函数。

.then((good)=>{ ()=>first()}).catch(err=>{console.log(err)}) }

这是你的代码应该喜欢的。

function second(){
return new Promise((res,rej)=>{
    setTimeout(()=>{res(),1500})})
    .then(()=>{()=>first()})
    .catch(err=>{console.log(err)})}

【讨论】:

    【解决方案2】:

    试试这个方法

    index.js

    const  first  = require("./first");
    
    first.first();
    

    first.js

    const  second  = require("./second");
    
    module.exports.first=function(){
        /* logic or code */
        return second.second();
    }
    

    second.js

    const  first  = require("./first");
    
    module.exports.second=function(){ 
        return new Promise((resolve, reject)=>{
            setTimeout(()=>resolve(), 1500)
        })
        .then(()=> {
            first.first()
        })
        .catch(err => {
            // Here's the first is not a function
            console.log("Error here!!: ", err)
        })
    }
    

    【讨论】:

    • 没有。我得到了意外的令牌导出。您所说的导出来自对 nodejs 后端无效的反应
    • @alex 很抱歉给您带来不便,我已经编辑了我的代码,请检查一下
    • 您好,我根据您的回答让它工作,而不是在 second.js 中调用 first(),它应该是 first.first()。请更新它,以便我可以在之后验证它。谢谢
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多