简体   繁体   中英

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. 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.

/* 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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