函数返回一个空数组

我找不到这个函数的bug。 它每次都返回一个空数组。 希望可以有人帮帮我。

https://gist.github.com/podkopaev/8406346

portal.getHosterByStream = function(stream, callback) { request(URL + stream, function (error, response, body) { if (!error && response.statusCode === 200) { var hoster = []; var $ = cheerio.load(body); var information = $('body div[id=frmMain] div[id=dontbeevil] div[id=Vadda]').html(); var items_hoster = $(information).find("ul[id=HosterList]").html(); $(items_hoster).each(function (i, item) { var rel = $(item).attr('rel'); if (rel != undefined) { request(MIRROR + rel, function (error, response, body) { if (!error && response.statusCode === 200) { var host = JSON.parse(body); var href = ""; var positionHref = 9; var i = 0; while (host.Stream.substr(positionHref + i, 1) != '"') { href = util.format('%s%s', href, host.Stream.substr(positionHref + i, 1)); i++; } hoster.push(href); } else { console.log('error second request'); } }); } }); callback(hoster); } else { console.log('error request page'); } }); } 

request()是asynchronous的,所以你在你的hoster.push(href)调用有机会执行之前调用callback(hoster)

所以,改变你的代码,不要调用callback(hoster)直到你所有的request()callback都完成了。

UPDATE

在你最近的要点中,你正在调用callback(null, 103); 在您的request呼叫之前呼叫他们的回叫和hoster

而不是rel.forEach ,使用async.eachSeries模式如下:

 async.eachSeries(rel, function(item, cb) { request(MIRROR + item, function (error, response, body) { if (!error && response.statusCode === 200) { ... hoster.push(href); } cb(); }); }, function(err) { // This won't get called until all the request callbacks are done. callback(null, 103); } );