by James
by James

Reputation: 99

Using asynchronous functions in try block

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

Upvotes: 0

Views: 74

Answers (1)

mrJoe
mrJoe

Reputation: 500

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

Upvotes: 2

Related Questions