节点testing.test不是一个函数

我试图调用另一个文件的function,但不pipe我做什么,它不会识别该function。 我明白了

uncaughtException:testing.test不是一个函数

//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甚至表明,我试图调用的是一个函数。 我哪里做错了?

你的variablestesting是一个函数(这就是你正在导出)。 你必须调用它才能得到你想要的对象。

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

select这两个选项中的一个或另一个。 将export作为函数保存,可以在每次调用函数时获取新的对象(如调用构造函数或工厂函数)。 直接导出对象允许所有用户或您的模块访问相同的对象。 那么,走哪条路最终取决于你想要什么types的devise。 您只需确保主叫方和被叫方协调一致地使用导出的值即可。

testing.js更改为以下内容:

 module.exports = { "test" : function() { return new Promise(function (resolve, reject) { console.log('worked!') resolve(resolve({'data': "success"})) }) } } 

现在有一个名为test的属性被导出,所以你可以按照你想要的方式在另一个文件中使用它: