Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

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

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();

Thanks Michael