【发布时间】:2015-10-15 20:19:59
【问题描述】:
我使用 Cheerio 每个函数来解析一些 URL 并将所有数据保存到 MongoDB 中。我的问题是cheerio每个功能都是同步的。而且我不知道解析何时结束开始做其他事情。那么如何让这些函数异步呢?
request(URL, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var posturl = $('a',this).attr('href');
$('article').each(function(i, element){
parse_url(posturl, i);
});
}
});
这是我的解析 URL 函数
function parse_url(url, i) {
request(url, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var title = $('article h1').text();
var postid = $('article').attr('id').substring(5);
var image = $('article img').attr('src');
var description = $('article p strong').text();
var json = { title : title, postid : postid, image : image, decription : description};
collection.insert(json,function (err, result) {
if (err) {
console.log(err);
} else {
}
});
}
});
}
【问题讨论】:
标签: node.js mongodb asynchronous cheerio