在callback中调用node.js中的助手函数?

我是相当新的编程与node.js,我不知道为什么我得到这个错误。 该函数看起来设置正确,我不认为我有任何asynchronous问题B / C这些应该考虑我自己的地方(我认为)的自variables。 我也尝试没有这个,使用简单的变种consolePrint(…)无论如何,这是我的代码在下面,错误日志下面。

/* global __dirname */ var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var self = this; //CALLING HELPER FUNCTION HERE var server = app.listen(8000, self.consolePrint(server)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/public', express.static(__dirname + '/public')); app.get('/', function (req, res) { res.sendFile(__dirname + '/public/views/index.html'); }); //---------------helper function(s)-------------------// self.consolePrint = function(serverVar){ var host = serverVar.address().address; var port = serverVar.address().port; console.log('Example app listening at http://%s:%s', host, port); } 

和错误:

 C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17 var server = app.listen(8000, self.consolePrint(server)); ^ TypeError: undefined is not a function at Object.<anonymous> (C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17:36) at Module._compile (module.js:460:26) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3 12 May 01:01:36 - [nodemon] app crashed - waiting for file changes before starting... 

这将解决问题:

 var server = app.listen(8000, function(){self.consolePrint(server)}); 

在定义之前,您正在使用该function。 将listen函数放在'self.consolePrint'赋值语句的下面,或者在使用它之前指定它,它将起作用。