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 trial

JavaScript

William Hurst
William Hurst
25,074 Points

Promise: How is then skipped on reject

The promise:

function theDisplayer(some) {
    console.log(some);
  }

  let thePromise = new Promise(function (theResolve, theReject) {
    let x = 1;

    if (x == 0) {
      theResolve("Resolved");
    } else {
      theReject("Rejected");
    }
  });

Using the promise:

  thePromise.then(
    function (value) {
      console.log('then');
      theDisplayer(value);
    }
  ).catch(function (error) {
    console.log('catch');
    theDisplayer(error);
  });

How is the function in "then" completely skipped and goes straight to the function in catch on reject? Because it's the first chained method, shouldn't it always execute? Unlike in the next example where the callback to be called is determined by the if statement in the promise.

This other way seems easier to understand: two functions are passed in "then". Next, using the if statement in the promise determines which callback is called.

  thePromise.then(
    function (value) {
      theDisplayer(value);
    },
    function (error) {
      theDisplayer(error);
    }
  );

1 Answer

Blake Larson
Blake Larson
13,014 Points

The then callback only fires if the promise is resolved. If it is rejected it skips the then and the catch block fires.

// RESOLVED PROMISE
const promise1 = new Promise((resolve, reject) => {
  resolve('Success!');
});

promise1.then((value) => {
  console.log(value); // expected output: "Success!"
}).catch(e => console.log(e)); // No error to catch



// REJECTED PROMISE
const promise2 = new Promise((resolve, reject) => {
  reject('Error!');
});

promise2.then((value) => {
  console.log(value); 
}).catch(e => console.log(e)); // expected output: "Error!"