JavaScript promises

What is a JavaScript Promise?
JavaScript promises are what their name says. You use them to make a promise to do something, usually asynchronously.
When the task completes, you either fulfill ๐ your promise or fail ๐ฃ to do so.
A Promise is a constructor function, so you should use the new keyword when creating a promise.
A promise takes a function as its argument with two parameters -
resolve and reject.
These two parameters determine the outcome of the promise.
Let's create a promise:
const myPromise = new Promise((resolve, reject) => {
});
A promise has three states:
1- pending โณ
2- fulfilled โ
3- rejected โ
The promise we created above ๐ is forever stacked in the pending โณ state because we did not add a way to complete the promise.
The resolve and reject parameters of the promise are used to do so.
resolve: means the promise is succeeded.
reject: means the promise is failed.
Both resolve and reject are methods that take an argument, that can be anything. Often it might be an object that you would use its data in your website or elsewhere. ๐
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
Handling a Promise
Promises are handled using then and catch:
1- then handles a fulfilled promise
2- catch handles a rejected promise
Promises are most useful when you have a process the takes an unknown amount of time in your code, like a server request.
When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server.
This can be achieved with the then method.
The then is executed immediately after your promise is fulfilled with the resolve. ๐
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
myPromise.then(result => {
console.log(result); // Promise was fulfilled
});
result is what has been passed to the resolve method as an argument, so here it's Promise was fulfilled.
And when your promise is rejected the catch method is called, It is executed immediately after a promise's reject method is called.๐
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
myPromise.catch(error => {
console.log(error ); // Promise was rejected
});
error is what has been passed to the reject method as an argument, so here it's Promise was rejected.
And that's it, I hope you learned the basics of promises in JavaScript.
Happy Coding.