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

Why don't you need a semicolon with fetch() and JavaScript promises?

Why doesn't Guil use semicolons following the fetch request or JavaScript promises in this video?

fetch('https://dog.ceo/api/breeds/image/random')
  .then(response => response.json())
  .then(data => console.log(data.message))

Would using them make the code not work?

1 Answer

Jesus Mendoza
Jesus Mendoza
23,274 Points

Hi Liz.

Sometimes in JavaScript you can chain function calls if the previous function call returns another function.

When you execute fetch function, it returns an object that has a few methods on it, including the method then and the method catch. In this case, you execute the fetch function, it returns an object with the then property on it so you "chain" it. The thenmethod also returns an object with the then and catch methods on it so you can chain then again and you can keep doing it as many times as you want (because the previous then method will always return a new object with the methods then and catch that you can continue chaining...

This would work too

const promise = fetch('https://dog.ceo/api/breeds/image/random'); // an object with the method then and catch (a few more too) is returned from this function call

promise
.then(response => response.json())
.then(data => console.log(data.message))

Let me know if I didn't make myself clear

Jordan Kittle
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jordan Kittle
Full Stack JavaScript Techdegree Graduate 20,143 Points

I have the same question. Why isn't there a semicolon at the end of everything (after all chained then methods) like this:

const promise = fetch('https://dog.ceo/api/breeds/image/random'); // an object with the method then and catch (a few more too) is returned from this function call

promise
.then(response => response.json())
.then(data => console.log(data.message));

I've added them to my code and it works either way. Is there any convention to using/not using them?