ceth
ceth

Reputation: 45295

Waiting for async call

I need to get the title of HTML page and I am using node-metainspector.

I have created a module:

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

And use it in my express application:

exports.add = function(req, res) {
  var url = req.body.url;
  console.log(url);
  console.log(parser.getTitle(url));
}

This code doesn't work correctly. The line console.log(parser.getTitle(url)); returns undefined. I think the reason is async nature of JS. inspector.on('fetch') is called after getTitle() finished. But I am new with node.js and I don't know what is the good pattern to solve this problem.

Upvotes: 1

Views: 172

Answers (1)

Jacob
Jacob

Reputation: 78850

You should convert getTitle into an asynchronous function by adding a callback parameter:

exports.getTitle = function(url, cb) {

  // ...

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

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

...then call it like this:

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

Upvotes: 2

Related Questions