Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this async function syntax for puppeteer? [duplicate]

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?

like image 370
dyoung Avatar asked Jan 25 '23 17:01

dyoung


2 Answers

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
> 
like image 165
Trott Avatar answered Jan 30 '23 11:01

Trott


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
like image 20
kiranvj Avatar answered Jan 30 '23 12:01

kiranvj