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 bine 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);
}
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 bine 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);
}
Share
Improve this question
asked Jul 14, 2018 at 14:38
user7014175user7014175
2
- 7 Your second snippet is not a self invoking function without parameters, it's just a block. For instance, a var declaration won't be scoped inside of your second example – Axnyff Commented Jul 14, 2018 at 14:42
-
async
attributes a function, so the initial syntax is as terse as it can get. – collapsar Commented Jul 14, 2018 at 14:42
3 Answers
Reset to default 11two way, we just can short a little :)
- 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');
}()];
- use [then] this is not absolute "anonymous"
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 pact way to do that. You have to have a function, not just a block.
No, you cannot. A block statement
only creates a new scope, just like an IIFE. An async function
however is executed asynchronously, that can't be done with a block.