Question on promises

so, in a promise you have the if else statement with a resolve and a reject. And from what I understand this is where you will write the code or even call a function to run if it’s resolved or rejected.

but then after that you have the .this and .catch which also takes in code to execute. This part confuses me with promises. From the looks of it, you have two spots to execute code depending on if the promise is successful or not.

I can’t really find a tutorial that explains this well.

If the condition is met in the if else statement code is already executed. So why do you execute more code in the .then / .catch?

let promiseExample = new Promise((resolve, reject) => {
  let num = 100

  if (num === 100) {
    resolve('is 100')
  } else {
    reject('not 100')
  }
})

promiseExample.then((successMessage => {
  console.log(successMessage)
})).catch((rejectMessage => {
  console.log(rejectMessage)
}))

This:

resolve('is 100')

is saying “pass this string to the then chain”.

and this:

reject('not 100')

is saying to pass that string to the catch chain. (Technically I think it is throwing an error which is “caught” by the catch, but that’s the idea.)

If the condition is met in the if else statement code is already executed. So why do you execute more code in the .then / .catch?

The resolve just says what data to return. But maybe you want to do something with that data. Maybe you want to use that Promise (or a function that returns that promise) in multiple places but want to do different things with the resolved values.