WittCode💻

A Common Promise Chain Mistake

By

Just because you don't explicitly return something in a Promise chain doesn't mean the chain will break.

Table of Contents 📖

Breaking the Promise Chain

A common mistake with Promise chains is forgetting that if you don't explicitly return something in the chain, the next step in the Promise will be executed with undefined as the value. To demonstrate, the code below gets some API data from JSON placeholader and logs the title of the first todo.

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => {
  return resp.json();
})
.then(todo => {
  console.log('Title of todo:', todo.title);
})
.catch((err) => {
  console.error('Something went wrong', err);
});

There are no issues here because we are returning a value. However, if we don't return something in the chain, the next step will be executed with undefined as the value. This will cause an error in this case as we are accessing a property of undefined.

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => {
  // return resp.json();
})
.then(todo => {
  // Cannnot read title because todo is undefined
  console.log('Title of todo:', todo.title);
})
.catch((err) => {
  console.error('Something went wrong', err);
});

In the code above, the catch statement will be hit because of the error. So, just remember that even if you don't explicitly return something in the chain, the next step in the Promise chain will be executed with undefined as the value. The chain will not break. If you want the catch statement to be hit, you can throw an error.

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => {
  // return resp.json();
})
.then(todo => {
  throw new Error('Woops!');
})
.catch((err) => {
  console.error('Something went wrong', err);
});