Tip: The order of then and catch matters

JavaScript, Function, Promise · Jun 12, 2021

Many if not most promise-related headaches come from incorrectly ordered Promise.prototype.then() and Promise.prototype.catch() methods. The order in which these methods are chained to a promise can lead to very different behaviors. Let's take a look at a very simple example:

const myPromise = () => Promise.reject('Oops!');
const logger = data => console.log(data);
const identity = data => data;

myPromise().catch(identity).then(logger); // LOGS: Oops!
myPromise().then(logger).catch(identity); // Nothing is logged

As you can see from this example, swapping the catch() and then() methods results in entirely different behavior, even though the promise has the same result. This is due to the fact that each chained method will result itself in a promise. This means that the first one will pass its result to the second, the second to the third and so on and so forth. While this might seem obvious when looking at an example like this one, many times it's overlooked and can result in hard to debug issues. This is especially true when the promise chain is long and complicated.

So, next time you are working with promises, try to think of then() and catch() methods in terms of promise chaining and remember that order matters!

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Promises

    JavaScript promises provide a modern and elegant way to to handle asynchronous operations. This snippet collection covers the basics of promises and how to use them in your code.

    Collection · 8 snippets

  • Resolve promise after given amount of time

    Creates a promise that resolves after a given amount of time to the provided value.

    JavaScript, Function · Jan 8, 2022

  • Pipe async functions

    Performs left-to-right function composition for asynchronous functions.

    JavaScript, Function · Oct 22, 2020

  • Debounce promise

    Creates a debounced function that returns a promise.

    JavaScript, Function · Oct 19, 2020