如何与多个相关功能正确使用异步使用异步...具有多种功能的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