Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

node.js - Puppeter how to prevent stopping program on error

Directly to the problem that I noticed while creating puppeteer automata. I check if element exists like this:

const check = async () => {
  let state = null
  await page.waitForSelector(els.configurationBtn)
    .then(res => res ? state = true : state = false)
    .catch(() => { state = false })
    enter code here

  return state
}

But it is not a smooth way to prevent stopping the program when page.waitForSelector throws an error.

My question is How can I wait for the element (check if exist) and return Boolean - true if the element exists and false if the element doesn't exist or when page.waitForSelector throws a timeout error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use await you can just use try...catch. No need for .then or .catch... that's the whole point of using await in the first place.

const check = async () => {
  try {
    return await page.waitForSelector(els.configurationBtn) != null;
  } catch {
    return false;
  }
}

Or just use .then and pass a second argument to it. The second function is called when the promise is rejected.

const check = () => page.waitForSelector(els.configurationBtn)
  .then(res => res != null, () => false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...