JavaScript Handling Errors

Tucker Blackwell
Tucker Blackwell
3,397 Points

Why is my fetchData function resulting in an error when I chain a .then() method with a console.log()?

The following function runs just fine...

const fetchData = url => { return fetch(url) .then(res => res.json()) .catch(err => console.log("problem: ", err)); }

but when I add a console.log(), it results in "app.js:15 Uncaught (in promise) TypeError: Cannot read property 'message' of undefined at"...

const fetchData = url => { return fetch(url) .then(res => console.log(res)) .then(res => res.json()) .catch(err => console.log("problem: ", err)); }

I can't figure out why this is happening? the line the error refers to is the very next instance that I use fetchData...

fetchData("").then(data => generateOptions(data.message))

1 Answer

Seth Kroger
Seth Kroger
56,320 Points

When you chain then()'s the next then() receives what the previous then() returns. However console.log returns nothing so there is nothing to pass to the next part of the chain.