Welcome to JS Bites!
This series is your bite-sized guide to mastering asynchronous JavaScript. We'll delve into concepts like callbacks, promises, and async/await
How JS Runs (Synchronously)
JavaScript code executes in a top-down manner, processing one line at a time. While this may seem fast to the user, allocating memory for each line can take some time behind the scenes. Each line relies on the previous line to finish executing before it can proceed.
Example:
const food = "pizza";
console.log(food);
Asynchronous Code
Asynchronous code allows JavaScript to perform operations without blocking the main thread. This means the program can continue executing other lines while waiting for an asynchronous operation, like fetching data from a server, to complete.
Example:
function asyncExample() {
console.log("First");
setTimeout(function() {
console.log("Second");
}, 2000);
console.log("Third");
}
asyncExample();
// Output:
// First
// Third
// (after 2 seconds) Second
Callback Functions
A callback function is a function passed as an argument to another function. The receiving function can then invoke the callback later, often after an asynchronous operation completes.
Example:
function callWithCallback(callback) {
setTimeout(function() {
const result = callback(4, 6);
console.log(result);
}, 2000);
console.log("First");
}
function callbackFunction(a, b) {
console.log("Second");
return a * b;
}
callWithCallback(callbackFunction);
// Output:
// First
// Second
// (after 2 seconds) 24
Callback Hell
Nesting callback functions deeply can lead to code that's difficult to read and maintain, often referred to as "callback hell."
Example:
Callback
inside Callback
inside Callback
inside Callback
function add(x,y){
return x+y
}
function subtract(x,y){
return x-y
}
function expectedResult(callBack, x, y){
return callBack(x,y)
}
console.log(expectedResult(add, 20, 10))
console.log(expectedResult(subtract, 30, 10))
Alternative Approaches
While callbacks are a fundamental concept, techniques like Promises and Async/Await offer more structured and readable ways to handle asynchronous operations. We'll explore these alternatives in future chapters.
Async Examples
Asynchronous code is commonly used for tasks like:
- Fetching data from APIs
- Calling backend servers
- Loading external files
- Setting timers and intervals