Handling Asynchronous Operation in Javascript
Javascript is one of the most widely used programming languages nowadays known for its versatility and dynamic nature. It is a dynamically written language and is widely used in developing dynamic web applications and websites. In this blog let us take a closer look at how we can handle asynchronous operations in Javascript.
But before diving into how we handle synchronous operations, let's first look at what asynchronous operations are.
Asynchronous Operations
Javascript is actually a single-threaded language which means that you can perform one function at a time and that too in a sequential manner. This means that if a part of code returns an error the execution of the remaining code will be hampered.
If somehow we can handle multiple executions during the same time then we can overcome this problem. This is what Asynchronous operations are. They do not affect the remaining part of the code which was to be blocked or hampered in any sort of way.
This is especially important in scenarios where tasks might take some time to finish, such as fetching data from a server, reading a file, or waiting for user input. In Javascript, we can handle asynchronous operations using 3 ways.
Callbacks:
Callbacks are functions passed as an argument to another function. Their time of execution depends on the completion of the operation. Let’s take a look at this code:
function doSomethingAsync(callback) {
setTimeout(function() {
console.log("Task is done!");
callback();
}, 1000);
}
function onComplete() {
console.log("Callback !!!!.");
}
doSomethingAsync(onComplete);
In the above code, we have defined a function
doSomethingAsync() and it is taking a callback function as a parameter. Inside
it a setTimeout function is written which will execute the callback function
after 1 second along with the console.log() function. Then a function
onComplete() is defined which will simply log “Callback !!!” on the console.
Later this function is passed as an argument in the function call of
doSomethingAsync(onComplete). So the output of the code will be
“Task is done!”
“Callback !!!”
Although callbacks are generally not recommended to perform asynchronous
operations since at times it leads to a situation named as “Callback’s Hell”.
Async/Await
One of the very easiest and cleanest methods of handling asynchronous requests is using Async and Await. Async is short for Asynchronous. So what actually happens is we use ‘async’ followed by a function’s definition. And inside this function we have a statement that is preceded with a keyword ‘await’. This denotes the code to halt the execution until this ‘await’ gets an answer or anything in return. Let’s see the syntax for it:
async function greet() {
return "Async!";
}
async function main() {
const message = await greet();
console.log(message);
console.log(‘Got it’)
}
main();
So here we have an async function greet() which will return ‘Async!’. Then we have another async function main() which is waiting for the greet() function to return the value and set it to a variable ‘message’ and then will log it to the console. At last we are calling the main() function.
So what do you think the output will be?
It’s easy:
Async!
Got it
Promises
The concept of promises in Javascript is really inspired by how promises work in our real lives. So we make a promise to do something for someone and then either complete the promise or not. Promises in Javascript have 3 states, Pending, Fulfilled and Rejected. Promises is a well structured concept but it requires a lot of typing. Let’s see the code for this:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Data received!");
} else {
reject("Error: Data not found");
}
}, 1000);
});
myPromise
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
So when we define a promise it takes 2 arguments and that is ‘reject ’ and ‘resolve’, they denote 2 different states. Going through the function so first we have created a promise named ‘myPromise’. Assigned ‘true’ value to a variable success. If the success is true then the resolve function will be executed else the reject function will be executed denoting there is some error.
After declaring a promise we have a then() and catch() functions to handle the after execution of a promise. So when resolve() is called it denotes success in our operation but what happens after resolve will be taken directly to then(). Now then() function is called with an argument ‘result’, this result is actually the data we wanted to extract. The catch() method is used to denote there was an error during the execution of promise.
This was all for how we can handle Asynchronous operations. Although to make the code look more cleaner and structured it is advisable to use Promises and Async/Await method.
Rest you can try out the one which method suits you the best depending upon the situation.
Subscribe our newsletter today!
So, this was all for this blog kindly leave any of your remarks and stay updated with our blogs to get some insightful pieces.
Check out our other JavaScript related Blogs:-
8 Key ES6 Features In JavaScript
String Methods In JavaScript
React vs Vue: Comparison Guide of Leading JavaScript Frameworks
Get In Touch with Us
Your email address will not be published.