在构建一个相当复杂的爬虫时,我偶然发现了我的代码控制流的问题。
下面的代码中发生了什么:1)请求一个 URL 2)从结果中抓取 NEWURL 3)将它作为第一个异步函数传递给可读性 API 4)问题来了——我永远不会得到下一个将 readabilityData 保存到数据库的异步函数
如何解决这个问题呢?我是 JS 新手,所以请随时指出我的代码的任何问题。
request(URL, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
NEWURL = data.find('a').attr('href');
readabilityData = {}
var articleUrl = 'https://readability.com/api/content/v1/parser?url=' + NEWURL + token;
async.series([
function(){
request(articleUrl, function(error, response, html) {
if (!error) {
readabilityData = response.toJSON();
}
});
},
function(readabilityData){
Article.findOne({
"link": url // here's the
}, function(err, link){
if(link) {
console.log(link)
} else {
var newArticle = new Article({
// write stuff to DB
});
newArticle.save(function (err, data) {
// save it
});
}
});
}
],
function(err){
console.log('all good — data written')
});
});
}
});