Aşağıdaki işlev, bir bağlantı dizisi alır ve uzak web sitesini tarar, sayfa başına 10 blog gönderimi alır ve ardından her blog yazısı için async.waterfall
'u kullanır.İç içe async.eachSeries yığınları yinelemeleri
working on www.mywebsite.com/
1
2
3
4
5
6
7
8
9
10
DONE PAGE
**************************************************************
working on www.mywebsite.com/posts/1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
DONE PAGE
**************************************************************
Ve bir her yineleme ile her şeye yeniden başlayarak on ile her sayfayı artırır:
// @param {Array} url
export default function getData(url, cb) {
const arrayOfPosts = [];
// Outer loop
async.eachSeries(url, (link, topLVLcb) => {
// Waterfall
async.waterfall([
// Collects links to posts
callback => {
request(link, (err, response, body) => {
console.log(`working on ${link}`);
const $ = cheerio.load(body);
// OVERALL 10 LINKS PER ONE BLOGPOST
$('.blogpost').each((i, element) => {
// build post ojbect
const post = {
content,
link,
comments: []
}
arrayOfPosts.push(post);
});
callback(null, arrayOfPosts);
});
},
// Looks for details in given post
(arrOfPosts, postDetailsCallback) => {
let counter = 1;
// Inner loop through 10 links
async.eachSeries(arrOfPosts, (post, eachSeriesCallback) => {
request(post.link, (err, response, body) => {
console.log(counter++);
const $ = cheerio.load(body);
$('.comment').each((i, element) => {
// build comment
const comment = {
author,
content
};
post.comments.push(comment);
});
eachSeriesCallback(null);
});
}, postDetailsCallback);
}
], err => {
console.log('DONE PAGE');
console.log('*************************');
topLVLcb(err);
});
}, (result, err) => {
if (err) {
throw err;
} else {
console.log('DONE ALL');
cb(arrayOfPosts);
}
});
}
Böyle çıkışını sağlar. Her sayfayı 10 kez taramak gerekir. Bazı geri bildirimleri karıştırdığımı düşünüyorum, ama tam olarak saatlerce anlayamıyorum. Bu benim ilk nodejs async kodum ve çok ezici.
ikinci line.const arrayOfPosts global ve her iterasyon için 0,10,20,30,40,50, .... büyür! – vkstack