How do promises program flow work?

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

You’re basically correct.

You pass in a callback function in the then and the catch to handle those cases, when they become available.

Consider this:

let p = new Promise(async (resolve, reject) => {
  const url = Math.random() > 0.5
    ? 'https://jsonplaceholder.typicode.com/todos/1'
    : 'https://something.that.isnt.a.real.url'
  console.log('asdf url', url)
  try {
    const data = await fetch(url).then(data => data.json())
    console.log(data)
    resolve(data)
  } catch(err) {
    reject(err)
  }
})

p.then(function(data) {
    console.log("success!!!");
    console.log('returned data', data)
  })
  .catch(function(err) {
    console.log("fail!!!");
    console.log('err:', err)
  })

The url has a 50/50 chance of working or failing. The try/catch block will catch the error and pass the relevant data back down.

1 Like