在回调中调用 node.js 中的辅助函数?

Calling helper function in node.js within callback?

我对使用 node.js 进行编程还很陌生,不太确定为什么会出现此错误。该函数看起来设置正确,我不认为我有任何异步问题 b/c 这些应该考虑到我放置的 self 变量(我认为)。我也确实尝试了 w/o,使用简单的 var 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...

您在定义函数之前使用它。把listen函数放在'self.consolePrint'赋值语句下面或者在使用之前赋值,就可以了。

这将解决问题:

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