Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 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.

question from:https://stackoverflow.com/questions/65601862/puppeter-how-to-prevent-stopping-program-on-error

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

1 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...