4

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?

dashingdove
  • 304
  • 1
  • 4
  • 15
  • 1
    The term you want to google for is IIFE. IIFE has nothing to do with asynchronous but in this case it is used with an asynchronous function. Normally you'd call an IIFE synchronously. The whole point of an IIFE is to create a new scope so that variables inside that function would not be visible to everything else outside – slebetman Sep 24 '20 at 04:13
  • 1
    It's an async immediately invoked function expression. See http://benalman.com/news/2010/11/immediately-invoked-function-expression/ for an explanation. It just creates an async function scope to contain some code that you want to be isolated in its own scope or, in this case, you want to be async. It's shorthand for defining a named function and then calling it. – jfriend00 Sep 24 '20 at 04:14

2 Answers2

5

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
> 
Trott
  • 66,479
  • 23
  • 173
  • 212
3

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

  1. This function is used to init some code and not used anywhere else.
  2. To get the benefits of arrow functions
kiranvj
  • 32,342
  • 7
  • 71
  • 76