2014-01-16 134 views
1

我找不到这个函数中的错误。它每次都返回一个空数组。 希望有人能帮助我。函数返回一个空数组

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

回答

2

request()是异步,所以你打电话之前callback(hoster)任何你hoster.push(href)调用得到执行的机会。

因此,将您的代码更改为不要拨打callback(hoster),直到您的所有request()回调完成。

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); 
    } 
); 
+0

可以请你帮助我的代码。我是node.js的新手,现在尝试修复这个bug一个星期。 – deno

+0

@ user3197431我的回答是否帮助您了解代码中的问题? – JohnnyHK

+0

是的,它帮助我了解问题。我试图找到异步库的解决方法,但它不适用于我。 – deno