Promise in JavaScript
In the world of web development, JavaScript plays a crucial role. When it comes to handling errors, one of the most important aspects is using promises in JavaScript. Think of promises in JavaScript like real-life promises, as explained in the diagram below.
This blog will explain how to handle errors and use promises in JavaScript. We’ll cover the basics like syntax, asynchronous functions, and resolving promises. In technical definition we can say “The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.”
A Promise is 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.
The pending promise will soon be fulfilled with a value or rejected with a reason (error). When either of these options happen, the handlers queued up by a promise’s then method will be called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
We will Discus more in examples
Understanding Asynchronous Operations with Promises in JavaScript:
1. Practical Example
const promiseOne = new Promise(function(resolve, reject){
//Do an async task
// DB calls, cryptography, network
setTimeout(function(){
console.log('Async task is compelete');
resolve()
}, 1000)
})
promiseOne.then(function(){
console.log("Promise consumed");
})In this awesome code snippet, we’re creating a promise called `promiseOne`. Inside this promise, we’re simulating an exciting asynchronous task using `setTimeout`. You can use promises to handle operations like database calls, cryptography, or network tasks. The asynchronous task, shown by `setTimeout`, finishes after 1000 milliseconds and logs “Async task is complete” to the console. We then happily call the `resolve()` function to indicate that the promise has successfully completed its operation.😀
Next, we get to use the promise using `promiseOne.then()`. Once the promise is fulfilled, the callback function inside `then()` is activated, logging “Promise consumed” to the console.
This code is crafted to showcase the flow of asynchronous operations with promises in JavaScript, highlighting the importance of resolving the promise to indicate task completion before it can be consumed.
Understanding Promises and Resolving Functions:
Promises contain a resolve and reject function, providing flexibility for asynchronous tasks. The resolve function executes when the promise is fulfilled, while the reject function handles any errors. Now question can we pass any data through the resolve function while it executes? Yes We can send Array , Objects etc. Lets See in the below code
const promiseTwo = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({ username: "Chai", email: "chai@example.com" })
}, 1000)
});
promiseTwo.then(function(user) {
console.log(user);
});Output:
Inside the Promise, there’s a setTimeout function simulating an asynchronous task with a 1-second delay. When this task is complete, resolve is called with an object containing user data.The Promise is then consumed using .then(). When the Promise resolves (after the asynchronous task is completed), the provided function inside .then() is executed. It receives the resolved data (in this case, the user object), and it logs this data to the console.
So, resolve is essentially confirming the successful completion of the asynchronous task and passing the resolved value (in this case, the user object) to the .then() handler for further processing.
Understanding Promises and Error Handling in JavaScript
In this topic, we will create and handle promises using the resolve and reject functions. We will learn how to pass data and handle errors within promises. So Lets Get started with the code
const promiseFour = new Promise(function(resolve, reject){
setTimeout(function(){
let error = true
if (!error) {
resolve({username: "Arapndev", password: "1234567"})
} else {
reject('ERROR: Something went wrong')
}
}, 1000)
})
promiseFour
.then((user) => {
console.log(user);
return user.username
}).then((username) => {
console.log(username);
}).catch(function(error){
console.log(error);
}).finally(() => console.log("The promise is either resolved or rejected"))In the given example, we have a Promise promiseFour with asynchronous logic inside its executor function. This Promise resolves with a user object if there is no error, and it rejects with an error message if there is an error. The code then uses the .then(), .catch(), and .finally() methods to handle the resolution, rejection, and cleanup actions.
Get Arpandev’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s explain one by one:
a)Two .then() Method:
.then((user) => {
return user.username;
})
.then((username) => {
console.log(username);
})- The first
.then()handles the resolution ofpromiseFour. If the promise resolves successfully (i.e., no error), it returns the username. - The second
.then()is chained to the first one, and it receives the returned username. It logs the username to the console.
b).catch() Method:
.catch(function(error){
console.log(error);
})The .catch() method is used to handle the rejection of promiseFour. If there is an error during the execution of the promise, this block will be executed, logging the error message to the console.
c).finally() Method:
.finally(() => console.log("The promise is either resolved or rejected"))The .finally() function is executed no matter if the promise is resolved or rejected. It is often used for cleanup tasks. In this instance, it logs a message indicating the resolution or rejection of the promise.
In summary, .then() is used to handle the resolution of the promise and can be chained for sequential operations. .catch() is used to handle rejections, and .finally() is used for code that should be executed regardless of whether the promise is resolved or rejected.
So Let’s Discuss the output
Here, if the error is true in the program, it will execute the else part, which includes the reject function with an error message. This will be caught by the catch function, responsible for handling and logging the error in the console. That’s why it’s printing “ERROR: Something went wrong”. On the other hand, the finally block always executes, whether there is a resolve or rejection, which is why it’s printing “The promise is either resolved or rejected” in the console.
So, does the tutorial end here? Yes, most educators do end here, but there is another way to handle errors and fulfill the promise that is always ignored. Actually, we don’t often use it. I will cover all of those. Isn’t it interesting? Let’s get started.
const promiseFive = new Promise(function(resolve, reject){
setTimeout(function(){
let error = true
if (!error) {
resolve({username: "javascript", password: "123"})
} else {
reject('ERROR: JS went wrong')
}
}, 1000)
});
async function consumePromiseFive(){
try {
const response = await promiseFive
console.log(response);
} catch (error) {
console.log(error);
}
}
//Calling the fuction
consumePromiseFive()Yes, we can use `async` & `await` keyword to consume the promise also, We have to use try catch block to handle the error .
Lets try to understand it
async function consumePromiseFive(){
try {
const response = await promiseFive
console.log(response);
} catch (error) {
console.log(error);
}
}The consumePromiseFive function is an asynchronous function that uses await to consume the promiseFive. It tries to await the resolution of the promise and logs the response if successful. If there's an error during the execution of the promise, it catches the error and logs it to the console. This structure simplifies asynchronous code, making it read more like synchronous code with error handling.
Soo that’s it……………………….
“There is no end to learning, but there are many beginnings”
― Tim Johnson,










