gpt4 book ai didi

javascript - module.exports 函数在另一个文件的 require 之后未定义

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:02 24 4
gpt4 key购买 nike

大家好,我从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
}

第二.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
}

该错误是在第二个.js 文件的 catch 中抛出的。它说:这里错误!!:TypeError:第一个不是函数

最佳答案

试试这个方法

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)
})
}

关于javascript - module.exports 函数在另一个文件的 require 之后未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56089157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com