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 trialLiz Laffitte
23,691 PointsWhy 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
23,289 PointsHi 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 then
method 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
Full Stack JavaScript Techdegree Graduate 20,148 PointsJordan Kittle
Full Stack JavaScript Techdegree Graduate 20,148 PointsI have the same question. Why isn't there a semicolon at the end of everything (after all chained then methods) like this:
I've added them to my code and it works either way. Is there any convention to using/not using them?