函数返回一个空数组

时间:2014-01-16 19:32:33

标签: node.js

我找不到此功能中的错误。它每次返回一个空数组。 希望有人可以帮助我。

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');
        }
    });
}

1 个答案:

答案 0 :(得分:2)

request()是异步的,因此您需要在callback(hoster)次调用有机会执行之前调用hoster.push(href)

因此,在完成所有callback(hoster)回调之前,请将代码更改为不调用request()

<强>更新

在您的最新要点中,您在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);
    }
);