Javascript understanding promises

I am confused with promises in javascript … like taking example from codecademy exercises … We use promise in checkinventory function which checks if items in orders are in stock and then provids output …

Wouldn’t directly using if / else do that same thing in less than half lines of code ? Why complicate things unnecessarily ?

True, but promises are asynchronous. They allow the rest of your code to continue while waiting till the promise has been resolved

this becomes very useful when you need to do something slow (making a network request to a server), without blocking the rest of your application

Its possible the exercise choice to over-complicate something that could be done simple to not introduce to many concepts at the same time


In the Codecademy lessons, they don’t actually use promises like they would be used in the real world. However, they just want you to get a good understanding of its syntax, and how it works (they also mention a few times how it would work in the real world)

Promises are used when fetching data from somewhere else - this could be your database, an API, etc.

Let’s just say you are fetching data from your database - you want to know how many users signed up to your program. To do that, you would simply take the number of users in your database, but this could take a bit of time (a few seconds). So, you would use all the methods that Codecademy tought you in the lessons (either .then() / .catch() or async/await), to handle the retrieval of data from your database

1 Like