Promise in javaScript is a way to handle asynchronous operations, such as fetching data from server ,reading files or making a request from network. Promise helps you to write more readable and organized code when dealing with asynchronous tasks.
Here is a simple example: 1. Resolving a promise
const promiseOne = new Promise(function(resolve, reject) {
//this is the very common way to write promise
setTimeout(() => {
resolve("async task completed");
}, 1000);
});
NOTE:
// .then() block is connected to the resolve part of the promise
// simulate task completed after 1 sec
promiseOne.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error)
});
In this example, we create a Promise that resolves after 1 seconds, simulating a successful async task. The [.then()] block executes when the promise is resolved and in this case the [.catch] block will not be displayed as we have successfully completed the task.
- Rejecting a Promise
const promiseReject = new Promise(function(resolve, reject){
setTimeout(() => {
reject("sorry could not complete your task");
}, 1000);
});
promiseReject
.then((message) =>{
console.log(message);
})
.catch((error) => {
console.log(error);
});
In this code, when the promise is rejected with the message "sorry could not complete your task" the [.catch() block] will execute, and "sorry could not complete your task" will be logged to the console. The .then() block won't execute because the promise was rejected, not resolved.
NOTE
To summarize, the behavior of .then() and .catch() depends on whether the promise is resolved or rejected. If the promise is resolved, the .then() block executes. If the promise is rejected, the .catch() block executes.
Top comments (2)
Very informative!
Good👍