r/learnjavascript • • Oct 18 '26

Promises

Understanding the concepts like functions, objects, arrays etc has been easy so far but promises are making my head hurt. Is it supposed to be this confusing? Did u guys struggle with it too when u were first learning it.

9 Upvotes

25 comments sorted by

View all comments

1

u/delventhalz Oct 18 '26

A common point of confusion for new JS devs is how asynchronous code is handled. Promises address some pain points of the old callback pattern, but they don't save you from learning how asynchronous code works. So let's start by talking about that.

The Event Loop

In JavaScript, there is a built in feature called an "event loop". You basically hand this event loop a function you want to run later, and it runs it once triggered by some external process. The simplest way to interact with the event loop is setTimeout. Go ahead and copy the following code into your console. It will probably do more or less what you expect.

setTimeout(() => {
    console.log('This will log in ten seconds!');
}, 10000);

What is happening here is that you are passing a function with a console.log in it to the event loop and asking the event loop, "Please run this later, once the timer process hits 10 seconds (i.e. 10,000 milliseconds)".

Straightforward enough, but it quickly gets more complicated. For example, what will this code log?

console.log('A');

setTimeout(() => {
    console.log('B');
}, 10000);

console.log('C');

You might suspect the answer. It's not "A B C", as just reading the code top to bottom would tell you, but "A C B". This makes a fair amount of sense when we consider the event loop. We do not run the "B" log directly. It is in a function we passed to the event loop. The event loop will run it later, once the timer elapses.

Okay, but what if we made the timer zero?

console.log('A');

setTimeout(() => {
    console.log('B');
}, 0);

console.log('C');

Now will it log "A B C" because the timer elapses instantly? No! It still logs "A C B". Importantly, the event loop has no way to interrupt code that is currently running. So this code will finish, including logging "C", before the event loop ever gets a chance to check the timer.

For a deeper dive on the event loop I highly recommend Philip Roberts's talk, which is less than 30 minutes long and very approachable.

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Promises

Okay, so let's look at a more realistic asynchronous example with Promises and fetch.

fetch('https://dog.ceo/api/breeds/image/random')
    .then(response => {
        return response.json();
    })
    .then(json => {
        console.log('Dog image URL:', json.message);
    });

This is fundamentally not much different from the earlier setTimeout example. We call fetch with a URL, which is saying to the event loop, "Please run a function later, once the HTTP process gets a response". Where is the function though? It's what we passed to the first "then".

This is the little sleight of hand Promises perform in order to deal with what was once a common asynchronous pain point: nested callbacks. The response.json function in that first "then" is also asynchronous. It says to the event loop, "Please run a function later, once all the bytes in the response body have been received and parsed as JSON". If we handled this with plain callbacks, we would have to nest them.

// Not real code! Fetch does not support plain callbacks!
fetch('https://dog.ceo/api/breeds/image/random', response => {
    response.json(json => {
        console.log('Dog image URL:', json.message);
    });
});

This is maybe fine with just two functions, but quickly gets unwieldy with many asynchronous operations you have to run one after the other. With a Promise, the "then" method not only takes a callback function, it also returns another Promise. This allows you to create an unnested chain of "then" methods, each with their own callback, and each will execute only after the previous callback.

What could be easier?

Async/await

These days, JS devs rarely work with the "then" method on Promises directly. They instead use the async/await keywords.

const logDogUrl = async () => {
     const response = await fetch('https://dog.ceo/api/breeds/image/random');
     const json = await response.json();
     console.log('Dog image URL:', json.message);
};

logDogUrl();

Remember when I said the event loop has no way to interrupt code that is currently running? Well I kind of fibbed. JavaScript has a kind of esoteric feature called "generator functions", which are essentially interruptible functions. You can choose yield-points in them, and they will pause at those points, and then resume from where they left off later when you call them again. Async/await is built on these pause-able generator functions.

So in the example above, when we hit that first await, we are pausing the function and passing control to the event loop. Later, when the fetch Promise resolves, the event loop will resume our function. This allows us to write code that looks very much like synchronous code, but under the hood it is still Promises and the event loop.