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.

Hey mate,
TBH I think Promise syntax is a complicated way of teaching Promises and new Promise also makes it more confusing :slightly_smiling_face:

How about we try async await

// 1. Request new emails
// 2. Pause the function at the await and let other code run
// 3. Save the result to new_Mail and resume the function when the emails are received
// 4. Pause the function return at the await until emails converted to JSON
// 5. return the decoded emails
//6. If the internet/ wifi disconnects catch the error and return an error object to the other code that called the function

async function refresh_Mail( ){
  try{
     let new_Mail = await fetch(“email.com”)
     let decoded = await JSON.parse(new_Mail)
     return decoded
    }
   catch{ return { status: “offline”, body: {}}
   }
}

So every time you see the await word the function will pause while something else is being done (network, parsing ect) and the let variable is storing a new Promise that automatically rejects if theres an error…. which will be caught be catch

1 Like

thank you.

1 Like