简体   繁体   English

为什么我的代码在等待后没有被执行

[英]why does my my code not get executed after await

In my scraping code, the second console print never gets executed, I'm unsure of what I'm doing wrong here, I'm new to the async and promises in javascript.在我的抓取代码中,第二个控制台打印永远不会被执行,我不确定我在这里做错了什么,我是 javascript 中的异步和承诺的新手。 ( the download picture function works ) (下载图片function作品)

async function scrape() {
  // ...
  await page.goto(URL, { waitUntil: "networkidle2" });

  let picturetest = true;
  if (picturetest) {
    console.log("this gets printed");
    await downloadPictures(page);
    console.log("this never gets printer");
  }
}
// await browser.close();

scrape();

async function downloadPictures(page) {
  const elements = await page.$$(
    "body > table > tbody > tr:nth-child(3) > td > form > table > tbody > tr:nth-child(2) > td:nth-child(2) img"
  );
  for (let i = 0; i < elements.length; i++) {
    // get screenshot of a particular element
    await elements[i].screenshot({ path: `${i}.png`, quality: 100 });
  }
}

There are two possibilities:有两种可能:

  1. The downloadPictures function is caught in an infinite loop downloadPictures图片 function 陷入无限循环
  2. An exception is being thrown and is not being caught抛出异常但未被捕获

Given that your loop looks fairly straightforward, you should focus on #2 first.鉴于您的循环看起来相当简单,您应该首先关注#2。 Start by adding a top-level error handler, where you currently invoke scrape() :首先添加一个顶级错误处理程序,您当前在其中调用scrape()

scrape().catch((error) => { console.error(error); });

This may or may not reveal the problem.这可能会或可能不会揭示问题。 You can narrow in on it by adding try/catch blocks around the individual await lines:您可以通过在各个await行周围添加 try/catch 块来缩小范围:

try {
  await someAsyncCall();
} catch (error) {
  console.error('someAsyncCall failed', error);
}

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

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