Hey there! Are you new to JavaScript? Well, this post is right for you! Mastering promises is a must if you want to become a JavaScript developer!
A Promise represents a value that's unknown now that may become known in the future; in other words an asynchronous value.
A Promise is always in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
Now, let's imagine you're hungry (I am now actually) and you're about to order food using a delivery app. You open the app. You find what you want and click order. At that moment, the restaurant/app makes a Promise
that they will deliver you food. While you're waiting, the delivery is pending
. In the future, if everything goes according to plan the restaurant/app will resolve
to deliver you food at which point your order has been fulfilled
. But in some cases, the restaurant/app might reject
your order in which case you'll have to order something else. Either way, the original request is finally settled.
More technical explanation
Now, let's explain it in a more technical language. As a developer, you create a Promise to represent an asynchronous value. But, what you'll actually do more often is consuming promises to use the result of an asynchronous operation in your code.
Let's create a Promise.
const food = new Promise((resolve, reject) => {
//āļø*
if (delivered) {
resolve("food delivered š„");
// resolve fulfills promise with passed value
} else {
reject("you're still starving... š");
// reject triggers when operation fails
}
});
*š executor, f-on that resolves a value or rejects (error)
Now let's consume the Promise.
food
.then(value => {
console.log(value); // food delivered š„
})
.catch(error => {
console.log(error); // you're still starving... š
})
.finally(() => {
console.log("all settled!");
});
then
is a function that handles fulfilment. catch
handles rejection; catches the error. And finally, finally
is there if you want to run some code no matter what.
I hope this helped you get the basic knowledge, an overview of JavaScript Promises :)
As always, any feedback is greatly appreciated!
Have a great one,
Dalibor
Top comments (5)
Thank you for sharing! This definitely invites further exploration and use once Iām more experienced. Iām fairly new to JavaScript so Iām still in love with it.
Good luck with mastering JavaScript, you'll be in love with it even more! And don't give up!
Thank you! It's really an amazing language. I did my first Stack Overflow answer yesterday dealing with some of the basics of selection. I can't wait to read more of your contributions here!
I have a question "what happens to finally if the promise fails?"
It runs when the promise is settled, no matter the outcome.