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!

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 accountSign in
Already have an account? Sign in here.
Sign In Now