繁体   English   中英

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

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

在我的抓取代码中,第二个控制台打印永远不会被执行,我不确定我在这里做错了什么,我是 javascript 中的异步和承诺的新手。 (下载图片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 });
  }
}

有两种可能:

  1. downloadPictures图片 function 陷入无限循环
  2. 抛出异常但未被捕获

鉴于您的循环看起来相当简单,您应该首先关注#2。 首先添加一个顶级错误处理程序,您当前在其中调用scrape()

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

这可能会或可能不会揭示问题。 您可以通过在各个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