Jump to content

How does promises program flow work in javascript?

Go to solution Solved by zzixp,

You have it right! Asynchronous JS is tough, I still get super confused by it and always have to look at examples. Another thing that might be confusing is when you actually want to use asynchronous code. In this example, there's no benefit to using promises versus just a regular if statement. However, when you start relying on other peoples' code, the promise API provides a standard way to handle errors. 

 

Pretend that your friend wrote a function that attempts a connection to a database. With the promise API, you don't have to care about how they do it, you're just responsible for handling possible errors.

 

try {
	let conn = await connectDB() // call your friend's code
    ... // do stuff!
} catch (err) {
	console.error(err)
}
  
// OR
connectDB.then((connection) => {
  ...
}).catch((err) => {
  console.error(err)
})

This article does a good job of explaining when/how you should use promises. Hope this helped!

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.

Link to post
Share on other sites

You have it right! Asynchronous JS is tough, I still get super confused by it and always have to look at examples. Another thing that might be confusing is when you actually want to use asynchronous code. In this example, there's no benefit to using promises versus just a regular if statement. However, when you start relying on other peoples' code, the promise API provides a standard way to handle errors. 

 

Pretend that your friend wrote a function that attempts a connection to a database. With the promise API, you don't have to care about how they do it, you're just responsible for handling possible errors.

 

try {
	let conn = await connectDB() // call your friend's code
    ... // do stuff!
} catch (err) {
	console.error(err)
}
  
// OR
connectDB.then((connection) => {
  ...
}).catch((err) => {
  console.error(err)
})

This article does a good job of explaining when/how you should use promises. Hope this helped!

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×