How do promises program flow work in javascript?

Promises syntax that I learnt:

let p = new Promise(function (resolve, reject) {
  let x = 20, y = 20;
  if (x == y) {
    resolve();

  }
  else {
    reject();
  }
})

p.then(function () {
  console.log("that's correct");
})

  .catch(function () {
    console.log("that's not correct");
  })

I don’t even understand what happens here, the flow control of here. My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens.

I’ve like read countless articles, banged my head against the wall but it’s still not getting inside my head. I feel so dumb for asynchronous javascript.

Please help me understand the program flow step by step in more detail.

The first line ties the p variable to the result of creating a promise of a function. A promise can have 1 of three states: pending, fulfilled (resolved), or rejected. When we invoke the function with p.then.catch, we say that we want one thing to happen when the promise is resolved (that’s the .then() as you guessed) and we want a different thing to happen if the promise is rejected (again, you were right on). In this case, while the Promise is asynchronous as always, it will resolve almost immediately because it’s a simple function that checks whether one value is equal to another, which it is.

In a theoretical, more practical example, I might create a Promise that fetches some data from a server about the current weather in a given city. I need to account for all three states. While it’s pending, I might want to let the user know with a little spinning animation. Then, if it is rejected, I’d still want to let the user know so that they’re not just sitting there waiting for a response that will never come - or I can even set my promise to retry a certain number of times on failure before finally displaying an error to the user. But if the response comes back resolved/fulfilled, I can finally give my user their weather info, as they requested.

I do this all asynchronously because I don’t want the rest of the website to not load; I just want the area where weather info is displayed to wait.

2 Likes