programmer
programmer

Reputation: 780

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.

Upvotes: 1

Views: 584

Answers (1)

Felix Kling
Felix Kling

Reputation: 816700

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

Upvotes: 1

Related Questions