gpt4 book ai didi

javascript - Node testing.test不是一个函数

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:08 25 4
gpt4 key购买 nike

我试图调用另一个文件中的函数,但无论我做什么,它都不会识别该函数。我明白了

uncaughtException: testing.test is not a function

//testing.js
module.exports = function(){
return{
"test" : function(){
return new Promise(function (resolve, reject) {

console.log('worked!')
resolve(resolve({'data': "success"}))
})
}
}
}

然后在任何其他文件中:

//other file
var testing = require("testing.js");
testing.test().then(function(data){
console.log(data)
})

我知道目录是正确的,我的 IDE 甚至显示我试图调用的是一个函数。我哪里出错了?

最佳答案

您的变量testing是一个函数(这就是您要导出的函数)。您必须调用它才能获取您想要的对象。

//other file
var testing = require("testing.js");
testing().test().then(function(data){ // added parens after testing()
console.log(data)
})

或者,将导出更改为直接导出对象,这样您就不必先调用函数来获取对象:

//testing.js
module.exports = {
"test" : function(){
return new Promise(function (resolve, reject) {

console.log('worked!')
resolve(resolve({'data': "success"}))
})
}
}

// then, this will work because testing is the actual object
var testing = require("testing.js");
testing.test().then(function(data){
console.log(data)
})

从这两个选项中选择一个或另一个。将 export 保留为函数可以让您在每次调用函数时获取新对象(如调用构造函数或工厂函数)。直接导出对象允许所有用户或您的模块都可以访问同一对象。因此,选择哪种方式最终取决于您想要什么类型的设计。您只需确保调用者和被调用者一致行动即可正确使用导出的值。

关于javascript - Node testing.test不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44810209/

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