我找不到这个函数中的错误。它每次都返回一个空数组。 希望有人能帮助我。
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()
是异步的,因此您在任何 hoster.push(href)
调用之前调用 callback(hoster)
获得执行的机会。
因此,请更改您的代码,以便在所有 request()
回调完成之前不调用 callback(hoster)
。
更新
在您的最新要点中,您在 request
调用调用其回调并填充 hoster
之前调用 callback(null, 103);
>.
使用 async.eachSeries
而不是 rel.forEach
以这样的模式:
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);
}
);
关于node.js - 函数返回一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21171145/