I'm looking at how to use Puppeteer for testing and all the code examples I come across use the following syntax:
(async () => {
//function body
})();
Now my question is not just what this does, as I understand what an asynchronous function is. What I want to know is what does this syntax mean and how is it parsed? I'm new to Node.js and Puppeteer and I've never seen this before. None of the tutorials I've found explain what is going on here.
I found this which explains the purpose of the =>
operator. So it seems that async () =>
is like a shorthand for async function ()
? I'm still confused as to why the whole thing is surrounded by parentheses and then followed by another pair of parentheses.
MDN shows that you can declare an asynchronous function in javascript using async function fname() {...}
. This seems straightforward. Why then not use this syntax? What is the difference?
The async function is surrounded by parentheses and then followed with a trailing ()
so that the function is immediately-invoked. See the article about IIFE on MDN for a more detailed explanation.
This is probably done because top-level await is not supported in current versions of Node.js.
$ node
Welcome to Node.js v14.12.0.
Type ".help" for more information.
> async function foo() { return Promise.resolve(true); }
undefined
> await foo()
await foo()
^^^^^
Uncaught SyntaxError: await is only valid in async function
>
What you see is a self executing anonymous function, also know as IIFE
(async () => {
//function body
})();
As you can see the function don't have a name. And its self executed as there is ()
at the end.
The same can be also written like this.
async function SomeFunctionName() {
//function body
};
SomeFunctionName();
Why then not use this syntax? What is the difference?
The reasons why your example don't use a function name and =>
(arrow func) as mentioned in above code might be this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With