简体   繁体   中英

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. ( the download picture function works )

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
  2. An exception is being thrown and is not being caught

Given that your loop looks fairly straightforward, you should focus on #2 first. Start by adding a top-level error handler, where you currently invoke 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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