Day 20: Consolidation 3
Lesson 5: IIFE
Immediately invoked function expression (IIFE for short) is actually something that I showed you on day 14 but we are going to review it here instead while we are talking about async.
Sometimes you want to use await
and you will get an error about needing to put await
inside a function marked as async
, so like this:
1const slowFunction = async () => { 2 const data = await slowFunctionCall(); 3 return data; 4};
But then you will mark the function as async
and you will get a complain about no top level async.
This is a really frustrating aspect of JavaScript that is slowly being resolved but will take a while. You can't have a function at the top of level of your code as async unless you put it in a module or put it in an IIFE.
This is because at the top level of your code there is nothing to unwrap the promise that an async
function returns, modules solve this (for reasons I won't go into now) but it's still not solved outside a module.
So you can either mark your JavaScript as a module like this <script type="module">
or learn the IIFE syntax:
1(async () => { 2 const data = await slowFunctionCall(); 3})();
This creates an async function with:
1async () => {};
Then immediately invokes it by putting it in ()
and then putting ()
after it:
1(async () => {})();
One day we won't need to do this but that day is not here yet.