简体   繁体   English

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

[英]Calling helper function in node.js within callback?

I'm fairly new to programming with node.js and am not quite sure why I am getting this error. 我对使用node.js进行编程非常陌生,并且不确定为什么会收到此错误。 The function looks to be set up correctly, and I don't believe I have any asynchronous problems b/c those should be account with the self variable I put in place (I think). 该函数看起来正确设置,并且我不认为我有任何异步问题,因为它们应该与我放置的自变量有关(我认为)。 I did try w/o that too, using simple var consolePrint(...) Anyways, this is my code below and the error log below that. 我也确实使用简单的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);
}

and error: 和错误:

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

You are using the function before defining it. 在定义函数之前,您正在使用该函数。 Put the listen function below the 'self.consolePrint' assignment statement or assign the before using it, it will work. 将侦听功能放在“ self.consolePrint”赋值语句下方,或在使用前分配它,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM