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.

APIs Create a Reusable Fetch Function

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Why doesn't the fetchData function need to be an async/await function?

I thought because there is a fetch() request inside the function, and because it is otherwise written as a synchronous event (regular function), that it had to be labeled as an async function with await after return and before fetch().

Here's the bit of code I'm referring to, specifically the first function:

function fetchData(url) {
  return fetch(url).then((res) => res.json());
}

fetchData("https://dog.ceo/api/breeds/image/random").then((data) =>
  generateImage(data.message)
);

fetchData("https://dog.ceo/api/breeds/list").then((data) =>
  generateList(data.message)
);

Thanks!

1 Answer

Steven Parker
Steven Parker
210,799 Points

The code here is using "then" to make sure the operations occur at the right time. Using "then" is similar to using "await" except that "then" fires a separate callback function after the promise resolves, but "await" pauses the current function until the promise resolves.

Steven, you are a legend! Thank you for everything you do here. I think I can speak for everyone when I say it helps out a lot.

Steven Parker
Steven Parker
210,799 Points

Thanks for the kind words, and happy holidays!   :christmas_tree: