Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript syntax for self invoking function with async

In JS in can write a self invoking arrow function with async like this:

(async () => {
    const promis = fetch(uri);
    console.log(await promis);
})();

A self invoking function without parameters I could also write like this:

{
   // do something
}

I was asking myself, is there a syntax to combine both and do something like this or is the first example already the shortest form?

// this is not working
async {
   const promis = fetch(uri);
   console.log(await promis);
}

2 Answers

two way, we just can short a little :)

  1. simple way
!async function () {
    console.log("e",'yibu');
}();

or like yours

(async  () => {
    console.log("e",'yibu');
})();

//maybe this is better then above
;(async function () {
    console.log("e",'yibu');
}());

//this is allmost same
;[ async function () {
    console.log("e",'yibu');
}()];
  1. use [then] this is not absolute "anonymous"
var x=async  () => 100;

x().then(
    e=>console.log({e})
);
like image 180
defend orca Avatar answered Aug 31 '26 15:08

defend orca


In the Javascript syntax, async is a modifier of a function. So, the only thing that can be async is a function.

Your second section of code is merely a block. It doesn't create a new function or a new function scope. And, per the Javascript syntax, you can't use async with a block. For example a variable declared in that block with var would still be hoisted to the top of the containing function scope because that doesn't create a new function scope.

Your third section of code does not work because async only works with functions, not with blocks (per the Javascript specification).

If you want an inline async section of code, you have to declare and execute a function and your first code block is a compact way to do that. You have to have a function, not just a block.

like image 35
jfriend00 Avatar answered Aug 31 '26 15:08

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!