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);
}
two way, we just can short a little :)
!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');
}()];
var x=async () => 100;
x().then(
e=>console.log({e})
);
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.
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