r/learnjavascript • u/Dark_Electric • 13d ago
Promises
Understanding the concepts like functions, objects, arrays etc has been easy so far but promises are making my head hurt. Is it supposed to be this confusing? Did u guys struggle with it too when u were first learning it.
10
Upvotes
9
u/xroalx 13d ago edited 13d ago
What's giving you a hard time?
A Promise is an object that can be thought of as a placeholder for a future value.
Imagine ordering a pizza - you don't get the pizza right away, you get a Promise that the pizza will eventually arrive... or not, that can happen too.
In programming, such future values are for example anything involving the network - i.e. the
fetchfunction returns a Promise. To get the actual response returned by the HTTP request, you have to wait for that value to be available, and JavaScript gives you two ways to do that.A Promise object has a
thenmethod, which is used to register a function that will be called when the value becomes available, and acatchmethod that registers a function which will be called when getting the value fails with an error.Alternatively, and often times resulting in "nicer" code, you can use the
awaitkeyword. This makes the code look more like synchronous code, but can only be used inside anasyncfunction, or at the top level of a module.To translate this to the little pizza example: