Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 等待异步调用_Node.js - Fatal编程技术网

Node.js 等待异步调用

Node.js 等待异步调用,node.js,Node.js,我需要得到的HTML页面的标题,我正在使用 我创建了一个模块: var MetaInspector = require('node-metainspector'); exports.getTitle = function(url) { var fullUrl = "http://" + url; var inspector = new MetaInspector(fullUrl, {}); var title = ''; inspector.on('fetch', funct

我需要得到的HTML页面的标题,我正在使用

我创建了一个模块:

var MetaInspector = require('node-metainspector');

exports.getTitle = function(url) {
  var fullUrl = "http://" + url;
  var inspector = new MetaInspector(fullUrl, {});
  var title = '';

  inspector.on('fetch', function() {
    title = inspector.title;
    console.log(title);
    return title;
  });

  inspector.on('error', function(error) {
    console.log(error);
  });

  inspector.fetch();
}
并在我的express应用程序中使用它:

exports.add = function(req, res) {
  var url = req.body.url;
  console.log(url);
  console.log(parser.getTitle(url));
}
此代码无法正常工作。行
console.log(parser.getTitle(url))返回未定义的

我认为原因在于JS的异步特性<代码>检查器。在getTitle()完成后调用on('fetch')
。但是我对node.js是新手,我不知道解决这个问题的好模式是什么。

您应该通过添加回调参数将
getTitle
转换为异步函数:

exports.getTitle = function(url, cb) {

  // ...

  inspector.on('fetch', function() {
    title = inspector.title;
    cb(null, title);
  });

  inspector.on('error', function(error) {
    cb(error);
  });
}
…那么就这样称呼它:

foo.getTitle(src, function(err, title) {
  if (err) { /* handle error */ }
  // Handle title
});