Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSteve Fau
5,622 PointsDifference 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
Full Stack JavaScript Techdegree Graduate 19,570 PointsThe 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
5,622 PointsSteve Fau
5,622 PointsThanks Michael