表刮板在函数返回之前不返回数据

时间:2018-09-15 19:25:38

标签: node.js discord.js

我目前正在开发一个使用node.js的Discord机器人,以从Dododex.com(游戏ARK中的生物数据库)中抓取信息。我发现了一个非常有用的库,名为table-scraper,该库从网页上抓取表格并将数据作为对象(或多个表的对象数组)返回。在后台,表格抓取器使用另一个名为x-ray的库以及常见的Web请求创建者request。请记住,我对节点或请求的工作方式知之甚少。

我正在做的是询问用户要获取数据的生物的名称。然后,我根据一系列生物(在文件/ JSON对象中具有的生物)检查该名称,以查看该名称是否有效。

现在,我要开始工作的是使用刮板机从属于该生物的dododex页面上刮取相关数据。 Table-Scraper确实可以与dododex一起使用,但是当我调用它来收集数据并将其放入对象时,它似乎开始抓取,但是随后让该函数返回一个空对象。如果程序返回后没有立即崩溃(由尝试访问一个空对象引起),从测试中我知道它将完成抓取,即使调用抓取的功能已经完成。

相关代码从此处开始:

const creature = getDinoFromName(args[0].toLowerCase(), arkdata); //Function explained below
if(creature.health.base == 404) //If the creature's name is invalid, getDinoFromName() will return a creature with health.base = 404
{
  console.log("unknown");
  unknownCreature(args, msg); //Tells the user that the creature is unknown
  return;
}
else
{
    //Outputs the data
}

这是收集数据的地方:

function getDinoFromName(name, arkdata)
{
  for(let i = 0; i < arkdata.creatures.length; i++) //Loops through arkdata, a json object with the possible names of all the creatures
  {
    if(arkdata.creatures[i].possible_names.includes(name)) //If the name the user provided matches one of the possible names of a creature (creatures can have multiple possible names, i.e. rex, t-rex, tyrannosaurus rex)
    {
      var creature;
      console.log("found");
      tableScraper.get("http://www.dododex.com/taming/" + arkdata.creatures[i].possible_names[0]).then(function(tableData)
      {
        console.log("scraped");
        var stats = tableData[1]; //tableData is an array of 3 tables matching the 3 html tables found on the site, tableData[1] is the one with the creature's stats. It looks like this: http://ronsoros.github.io/?31db928bc662538a80bd25dd1207ac080e5ebca7
        creature = //Now the actual creature object, parsed from tableData[1]
        {
          "health":
          {
            "base": stats[0]["Base (Lvl 1)"], //
            "perwild": stats[0]["Increase Per Lvl (Wild)"],
            "pertamed": stats[0]["Increase Per Lvl (Tamed)"]
          }
          //There is more data to parse but I only included hp as an example
        }
      });
      return creature;
    }
  }
  //If the creature name is not found to be one of the possible names, returns this to signify the creature was not found
  return {"health":{"base":404}};
}

运行代码会导致节点崩溃和错误

/app/server.js:320
  if(creature.health.base == 404)
TypeError: Cannot read property 'health' of undefined
at stats (/app/server.js:320:15)
at Client.client.on.msg (/app/server.js:105:7)

这里有些不可思议的事情,我真的不明白。任何帮助表示赞赏。

0 个答案:

没有答案