Asynchronous JavaScript
Sanket De
Posted on June 1, 2023
Callbacks
- In JavaScript, a callback is a function that is passed as an argument to another function and is executed later, typically after some asynchronous operation or when a certain condition is met.
- Callbacks are commonly used in JavaScript to handle asynchronous tasks like making API calls, handling events, and executing code after a certain operation completes.
function greet(name, callback) {
console.log('Hello, ' + name + '!');
callback();
}
function sayGoodbye() {
console.log('Goodbye!');
}
greet('Sanket', sayGoodbye);
- In the above example, we have two functions:
greet
andsayGoodbye
. - The
greet
function takes two arguments:name
andcallback
. - It logs a greeting message with the provided name and then calls the
callback
function. In this case,sayGoodbye
is passed as the callback function togreet
. - When
greet
is invoked with the name 'Sanket', it logs "Hello, Sanket!" and then calls thesayGoodbye
function, which logs "Goodbye!".
Promises
- In JavaScript, promises are used to handle asynchronous operations in a more structured way compared to callbacks.
- A promise represents the eventual completion (or failure) of an asynchronous operation and allows you to attach callbacks to handle the resolved value or the error.
function greet(name) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (name) {
resolve('Hello, ' + name + '!');
} else {
reject('No name provided!');
}
}, 2000);
});
}
greet('Sanket')
.then(function(message) {
console.log(message);
})
.catch(function(error) {
console.log('Error: ' + error);
});
- In the above example, the
greet
function returns a new Promise. - Inside the promise, we created an asynchronous operation using
setTimeout
. - If a name is provided, the promise is resolved with the greeting message. Otherwise, it is rejected with an error message.
Code Control
- In JavaScript, when an asynchronous operation, such as making an API call or waiting for a timer, is encountered, it is typically handled by the JavaScript runtime environment rather than directly controlled through code.
-
Here's a high-level overview of how the flow of data occurs in asynchronous operations:
- Synchronous Execution: JavaScript code is executed synchronously, line by line, in a single thread. Functions are pushed onto the call stack, and when a function call is encountered, it is executed and then removed from the stack.
- Asynchronous Operations: When an asynchronous operation, such as an API call, is encountered, it is offloaded to the browser's web API. The web API handles the operation asynchronously and continues executing the rest of the code.
- Callback/Event Handler: In asynchronous operations, callbacks or event handlers are typically registered to handle the completion or response of the operation. These callbacks are not executed immediately but are scheduled to be placed in the task queue once the operation is complete.
- Task Queue: The task queue (also known as the event queue) holds the callbacks or event handlers that are ready to be executed. Once the call stack is empty, JavaScript checks the task queue for any pending tasks.
- Event Loop: The event loop constantly checks if the call stack is empty. If the stack is empty, it takes the first task from the task queue and pushes it onto the call stack for execution.
- Execution of Callbacks: The callbacks or event handlers are executed one by one in the order they were added to the task queue. These callbacks can contain code that manipulates data, updates the user interface, or triggers further asynchronous operations.
- This flow allows JavaScript to handle asynchronous operations without blocking the main thread and ensures that callbacks are executed in the correct order.
References
💖 💪 🙅 🚩
Sanket De
Posted on June 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.