DEV Community

loading...

What's a promise? Exactly...

terrythreatt profile image Terry Threatt ・1 min read

What is a promise

If you have been learning Javascript or writing Javascript you have come across a piece of code called a promise. A promise is a foundation tool for writing Asynchronous Javascript. A promise is an object that is a proxy for an asynchronous task to be resolved and returned.

Why do we use promises

One purpose of using promises in your code is to preserve the execution of the lines of code to be processed when your data is ready. Javascript is single-threaded and a lot of use cases for the language are to process lots of user interactions. Promises help to keep those processes from unnecessarily blocking any other interactions while your promises are being fulfilled.

How to create a promise


let orderFood = new Promise((resolve, reject) => {
// a promise has three possible states = [Pending, Fulfilled, Rejected]
// upon creation the state is "Pending"
if (ingredients === "available") { 
resolve("Order coming right up!") // state is "Fulfilled"
} else {
reject("We are all out of ingredients for your order.") // state is "Rejected"
}
}
.then("Your food is ready") // Chaining - This is an instance method that runs an async task when run after our promise has been fulfilled 
.catch(Error("Here's a refund for your order we couldn't fulfill") // Chaining - This is an instance method that will provide error handling after a rejection in our promise. 

Enter fullscreen mode Exit fullscreen mode

So now you have more than a few things about how to use promises in Javascript. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with promises in Javascript.

Happy Coding,
Terry Threatt

Discussion (0)

pic
Editor guide