如何與多個相關功能正確使用異步使用異步...具有多種功能的JavaScript
這是我嘗試它不工作了,這是一個async.waterfall函數中:
function (urlsCreated, cb) {
var z, artist, title, added_on;
z = [];
async.mapSeries(urlsCreated, function (url, next) {
scrape_music.total_pages(50, url, function (array, total, extra) {
scrape_music.each(artist, title, added_on, array, url, function (result) {
});
});
}, function (z) {
console.log(z);
});
}
一切都好工作到這部分...
基本上urlsCreated是2個網址的陣列...
然後我叫mapSeries假設它會在它們之間迭代...
它應該工作的方式是,它遍歷數組中的每個url,然後爲每個url應該獲得url的總頁數,然後對於每個頁數添加到total_pages的數組參數/回調,應該在...內重複...
所以基本上數組是:urlsCreated (每個方法應該抓取每頁,預先包含在數組中的頁數),然後重複url的url數量創建...
任何幫助都很棒,目前沒有任何東西會被打印出來,並且基本上我只想要一個數組充滿scrape_music.each結果返回的對象。
EDIT ----
下面是這些功能的代碼。
//loop thrugh each page and find jquery elements that match
Scrape.prototype.each = function (artist, title, added_on, array, urls, cb) {
console.log('entered each');
console.log(array);
var $trs, list;
list = [];
this.page(array, urls, function ($page) {
//$trs selects all the rows from 1-50
$trs = $page('tr').slice(11, -3);
$trs.map(function (i, item) {
var result;
result = {};
result.artist = $page(item).find('td').eq(1).text();
result.title = $page(item).find('td').eq(2).text();
result.added_on = $page(item).find('td').eq(3).text();
list.push(result);
});
cb(list);
});
};
Scrape.prototype.total_pages = function (divide, url, cb) {
return request("" + url + config.url.pageQ + 0, function (err, res, body) {
if (err) { throw err; }
var page, select, match, total, matches, array, extra;
array = [];
page = cheerio.load(body);
select = page('tr').slice(9, 10);
match = page(select).find('td').eq(1).text();
matches = match.slice(-18, -14).trim();
total = Math.round(matches/divide);
extra = matches % divide;
for(x = 0; x < total; x++) {
array.push(x);
}
cb(array, total, extra);
});
};
//used to loop through all pages
Scrape.prototype.page = function (array, urls, cb) {
return array.forEach(function (i) {
return request("" + urls + config.url.pageQ + i, function (err, res, body) {
//console.log(urls + config.url.pageQ + i);
if (err) { throw err; }
cb(cheerio.load(body));
});
});
};
這是我不太清楚你的真正的問題是,但也許遞延/承諾可能會幫助:http://www.html5rocks.com/en/tutorials/async/deferred/ – jfriend00
我爲我的函數添加了代碼,但基本上異步不能讓每個函數在下一個之後發生,直到它們全部完成... – Lion789