我有节点代码,用于获取要爬网的网站列表,并在遍历结果时调用使用幻影编写的爬网函数。但是,在抓取函数返回结果之前,循环会迭代次数,并因此调用不能处理它的抓取函数的次数。我需要立即回答我的问题。 请有人带我离开这个井。node.js for循环在函数调用返回之前迭代因此创建对象问题
我的主网页代码
db.fetch_serviceEntity(function(serviceEntityData){
if(serviceEntityData!=""){
serviceEntityData.forEach(function(item){
console.log(item.website_url);
db.fetch_entityId(item.id,function(entityId){
crawler.getCount(item.website_url, item.name, function(rCount){
console.log("number of fresh reviews to crawl : ", parseInt(rCount) - parseInt(item.review_count));
if(rCount > item.review_count){
fetchReviews(item.website_url, entityId.id, parseInt(rCount) - parseInt(item.review_count), function(){
db.updateReviewCount(item.id, rCount, function(){
process.exit(0);
});
});
}
});
});
};
});
}
else {
console.log("No websites to crawl/database error");
}
process.exit(0);
});
我的检索功能是此
crawler.prototype.crawl = function(webUrl, callback){
console.log(webUrl);
this.driver.create({ path: require('phantomjs').path }, function (err, browser) {
return browser.createPage(function (err,page) {
return page.open(webUrl, function (err,status) {
console.log("opened site? ", status);
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function (err) {
// Wait for a bit for AJAX content to load on the page. Here, we are waiting 5 seconds.
setTimeout(function() {
return page.evaluate(function() {
//Get what you want from the page using jQuery.
var reviews = [];
$('li div.review').each(function() {
if($(this).find('div.ypassport').text()){
var d = new Date($(this).find('span.rating-qualifier').text().trim());
var temp = {
id : $(this).attr('data-review-id'),
entity_id : "",
user_id : $(this).attr('data-signup-object').split(":")[1],
}
reviews.push(temp);
}
});
return {
reviews: reviews
};
}, function (err,result) {
browser.exit();
callback(result);
});
}, 5000);
});
});
});
});
};
我使用节点幻像简单写作爬行功能
这里我的问题 - >因为循环将调用它的数量,爬取功能给我的错误,一些或其他物体未创建。 例如在代码中显示“createpage不是未定义的函数”,因此其含义是未创建浏览器对象。 有时它说“打开不是未定义的函数”,因此“页面”对象没有创建。
没有犯罪意图,但多数民众赞成在一些艰难代码阅读...尝试使用单独的函数或外部库,甚至去ES6和使用承诺。 – Drakoumel
是的尝试与承诺..谢谢。如果它会让你知道 – Mallikarjun
是的,试试承诺。 Q或蓝鸟图书馆是坚实的。这种类型的嵌套通常被称为末日金字塔:https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming) –