Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await an async function evaluation in PuppeteerSharp

In Puppeteer you can evaluate async functions:

await page.evaluate(async () => {
    // await some promise
});

Is there an equivalent in PuppeteerSharp? Using EvaluateFunctionAsync, the task completes before the promise resolves:

await page.EvaluateFunctionAsync(@"async () => {
    // await some promise
}");
like image 516
Eric Eskildsen Avatar asked Jun 29 '18 01:06

Eric Eskildsen


People also ask

Can you await an async function?

Async functions can contain zero or more await expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.

How do I add async-await to function?

The async-await syntax helps with readability, allowing you to write the code as if it were using synchronous call patterns. To enable this method of communication, you'll need to modify your function prototype. In the declaration of the function prototype, before the word function, add the keyword async.

Should you await all async functions?

There's no specific need to mark a function async unless you specifically need one of the benefits of an async function such as the ability to use await inside that function or the automatic error handling it provides.

Does async-await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.


1 Answers

That's the right way, for example:

var six = await page.EvaluateFunctionAsync<int>("async () => await Promise.resolve(6)");
like image 93
Meir Blachman Avatar answered Sep 24 '22 05:09

Meir Blachman