【问题标题】:Calling helper function in node.js within callback?在回调中调用 node.js 中的辅助函数?
【发布时间】:2015-07-22 20:46:28
【问题描述】:

我对使用 node.js 编程还很陌生,我不太清楚为什么会出现这个错误。该函数看起来设置正确,我不相信我有任何异步问题 b/c 这些应该与我放置的 self 变量有关(我认为)。我也确实尝试过,使用简单的 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...

【问题讨论】:

  • 你为什么不这样尝试..var server = app.listen(8000, function(){self.consolePrint(server)});

标签: javascript node.js asynchronous express callback


【解决方案1】:

这将解决问题:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 2015-11-09
      相关资源
      最近更新 更多