Asynchronous Javascript
Javascript is a synchronous, single-threaded language, meaning each line of code will be executed one after the other inside the call stack and on the main thread. If we wait for a time-taking code to finish, the entire code written after that particular line will be stuck until the last line is executed. This is called Blocking of Code. So, does that mean we cannot run asynchronous operations in Javascript?
That's where Callbacks come into the picture.
Introduction to Callbacks
Callbacks are introduced to handle the asynchronous operations in javascript.
A callback is a function that is passed inside another function as an argument to perform some actions.
Ex:- calling a function displayUser
with arguments as greetings(callback function)
displayUser(greetings)
displayUser
is taking the user's name as input and in return calls another function greetings.
function greeting(user){
console.log (`Hi ${user}, How are you?`)
}
function displayUser(callback){
let name='somi'
callback(name)
}
displayUser(greeting)
Here, greeting
is a callback function as it is passed as an argument to do some action.
An argument to setTimeout is also called a callback function
.
setTimeout(displayName,5000);
function displayName(){
console.log("My Name is",prompt(name));
};
Let's take another example where we have to call another function only when the previous function has finished executing.