Ladies and Gentleman, In this post we will understand and master Promises in JavaScript.
What's a Promise? π§
A Promise object represents the eventual completion or failure of an asynchronous operation. In simple language, a Promise is data returned by asynchronous functions.
let promise = new Promise((resolve, reject) => {
// Do something...
});
Promise States π€
A promise can have one of these states:
- Pending: This is the initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
Resolve / Reject
The Promise constructor takes in one argument: a callback with two parameters-resolve and reject.
- **resolve **when the Promise was fulfilles
- **reject **when something didn't work (e.g. an error ocurred)
General Structure π³
Take a look at how a Promise is generally structured:
let promise = new Promise((resolve, reject) => {
// Do something...
if(/* Everything went fine */) {
resolve("Task successful!");
} else {
// Well... something went wrong
reject("Something went wrong!");
}
});
NOW, LET'S RUN THE PROMISE FROM THE ABOVE CODE π
promise
.then((message) => {
// Print out the message if the
// promise is fulfilled
console.log(message);
})
.catch((error) => {
// Catch error is one occurred
console.log(error);
});
Here is a simple example of using Promise
let promiseToWashDishes = new Promise((resolve, reject) => {
// whether the dishes are clean or not
let clean = true;
if(clean) {
// Resolve promise if the dishes are clean
resolve("The dishes are clean!");
} else {
// Reject the promise if the dishes are dirty
reject("The dishes are still dirty!");
}
});
Let's run our example Promise:
promiseToWashDishes
.then((result) => {
console.log(`Great! ${result}`);
// Great! The dishes are clean !
})
.catch((result) => {
console.log(`Oh no! ${result}`);
// Oh no! The Dishes are still dirty!
});
Real World Example π€©
Chances are, you have already worked with the Fetch API! It uses Promises, too:
fetch("https://example.com/")
.then((response) => response.json())
.then((data) => {
// Do something with the data...
})
.catch((error) => {
// Something went wrong during the request!
});
Need Help
Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.
πThanks For Reading | Happy Coding β‘
Top comments (0)