JavaScript Asynchronous Programming with JavaScript Exploring Async/Await Convert Promise Handling to Async/Await

Steve Fau
Steve Fau
5,621 Points

Difference between anonymous async function and Async function assignment in the teacher notes?

I might be missing something, but what's the difference between these two?

Anonymous async function

const getData = (async function() {
  const response = await fetch('...');
})();

Async function assignment

const getData = async function() {
  const response = await fetch('...');
};

In the first example (anonymous async function), I'm looking at the () at the end, which is suggesting that we're invoking the whole thing, but I don't understand why we would like to do that.

1 Answer

Michael Kobela
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Michael Kobela
Full Stack JavaScript Techdegree Graduate 19,538 Points

The first example is an IIFE: https://developer.mozilla.org/en-US/docs/Glossary/IIFE

The function that was named getData is called immediately where is was declared, so you don't really need the const getData

(async function() {
  const response = await fetch('...');
})();

IIFEs are used so that you can enclose the scope of const response in the function instead of as a global variable.

Where as the second example is a normal function expression that does not get called until you do: getData();

Steve Fau
Steve Fau
5,621 Points

Thanks Michael