0

I have a puppeteer program, in which I have to call page.waitForSelector, which is an asynchronous function, to see if it throws any errors. But I assume, because a try-block is synchronous and it doesn't wait for an asynchronous function to be finished, even when I use await, it continues Executing the code after the try-block before even checking if there's an error. This is my code:

try {
    await page.waitForSelector("#captchaImage", {timeout: 6000});
}
catch {
    console.log("Your URL has changed");
    return;
}
console.log("You're still on the good site :)");

Is there a way to fix this problem or to make an asynchronous function synchronous (So it blocks code execution)?

1
  • 1
    page.waitForSelector must return a Promise (otherwise you couldn't await it), so why not just use the built-in catch method rather than a try/catch which, as you note, is designed for synchronous code, not async Commented Jul 21, 2019 at 10:57

1 Answer 1

2

In order to be asynchronous a function must return a Promise. Then it's possible to attach handlers like .then() or .catch() to handle return value when Promise is resolved or rejected, respectively. Another way of handling asynchronous actions is to await them and make current block of code to wait until the Promise is settled.

The first thing you have to do is to check if waitForSelector returns a Promise. It can return Promise explicitly in its return statement, or you can use async keyword in function definition to wrap the return value in the Promise:

async function waitForSelector(param1, param2) {
  // code goes here
  return result;
}

Then you can either attach .then() .catch() handlers or use await keyword to wait for result synchronously.

try {
    // assuming that it returns some value you want to process when function finishes
    let result = await page.waitForSelector("#captchaImage", {timeout: 6000});
    console.log(result);
}
catch {
    console.log("Your URL has changed");
    return;
}
console.log("You're still on the good site :)");

­

Note, that you cannot await a function in global scope, outside of a function. It means that your above code must be either placed inside another async function or wrapped in IIFE like given below:

(function() {
  //above code goes here
})();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, didn't even know this function exists! :)
I updated my answer with important note about where you're allowed to use await keyword. It's a common pitfall to use it in global context where it won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.