繁体   English   中英

async/await 函数意外返回

[英]Unexpected return of async/ await function

我正在制作的刮刀有一个注册路线来开始刮擦过程。 由于抓取过程很长,我决定创建另一个路由,我的前端将每 15 秒请求一次以获取数据。 我遇到的问题是,即使抓取完成,获取数据的路径也会返回一个空对象。 实际上,它应该返回抓取的数据,而不是返回 404 错误(请参阅下面的代码)。 我已经包含了额外的代码,以防它是问题的原因。

const scraper = async (email, password) => {
  let grades = [[], [], [], []];
  let category_weights = [];
  try {
    // try to scrape website
    // this block of code contains await functions
  } catch (e) {
    console.log(e);
    return;
  } finally {
    return {
      grades,
      category_weights
    };
  }
};

let result;

app.post("/api/register", (req, res) => {
  result = scraper(req.body.email, req.body.password);
  res.sendStatus(200);
});

app.get("/api/data", (req, res) => {
  console.log(result["grades"]); // undefined
  console.log(JSON.stringify(result, null, 4)); // {}
  result.hasOwnProperty("grades") ? res.json(result) : res.sendStatus(404);
});

该代码返回404状态代码,因为result是一个Promise ,并且它没有grades属性。

你必须等到承诺完成。 你可以使用await 这样,一旦抓取完成,对/api/data调用将返回数据,而不是404状态代码。

为了避免超时问题,您可以增加该特定路由的超时时间:

req.setTimeout(1000 * 60 * 5); // or whatever value you want

或者只是在/api/register被命中后立即结束请求,然后运行刮刀功能,等待结果。

app.post("/api/register", async(req, res) => {

    res.sendStatus(200);

    try {
        result = await scraper(req.body.email, req.body.password);

    } catch(e) {
        console.log('Scraper failed');
    }

});

app.get("/api/data", (req, res) => {
  console.log(result["grades"]); // undefined
  console.log(JSON.stringify(result, null, 4)); // {}
  result.hasOwnProperty("grades") ? res.json(result) : res.sendStatus(404);
});

这是Promise上的JSON.stringify将返回{}的证据

 console.log(JSON.stringify(new Promise(() => {}), null, 4)); // {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM