等待异步调用
Waiting for async call
我需要获取 HTML 页面的标题,我正在使用 node-metainspector。
我创建了一个模块:
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();
}
并在我的快递申请中使用它:
exports.add = function(req, res) {
var url = req.body.url;
console.log(url);
console.log(parser.getTitle(url));
}
此代码无法正常工作。行 console.log(parser.getTitle(url));
returns undefined
。
我认为原因是 JS 的异步性质。 inspector.on('fetch')
在 getTitle() 完成后调用。但是我是 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
});
我需要获取 HTML 页面的标题,我正在使用 node-metainspector。
我创建了一个模块:
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();
}
并在我的快递申请中使用它:
exports.add = function(req, res) {
var url = req.body.url;
console.log(url);
console.log(parser.getTitle(url));
}
此代码无法正常工作。行 console.log(parser.getTitle(url));
returns undefined
。
我认为原因是 JS 的异步性质。 inspector.on('fetch')
在 getTitle() 完成后调用。但是我是 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
});