Asynchronous
JavaScript is single-threaded, which means it executes one operation at a time. This can be problematic when dealing with time-consuming tasks, such as fetching data from APIs or performing heavy computations. Asynchronous programming allows us to execute tasks concurrently without blocking the main thread, ensuring that our applications remain responsive.
Built-in Async Functions
setTimeout and setInterval are built-in JavaScript functions that allow you to delay the execution of code or repeat it at specified intervals.
Syntax: setTimeout(<function>, duration)
Callbacks have been the traditional way of handling asynchronous operations in JavaScript. A callback is a function passed as an argument to another function, which will be executed once the asynchronous task completes.
function stepOne(callback) {
setTimeout(() => {
console.log('Step One Complete');
callback();
}, 1000);
}
stepOne(() => console.log('callback after step 1 completed'));
Callbacks Hell
While callback get the job done, nested callbacks can lead to the dreaded "callback hell," making code hard to read and maintain
function stepOne(callback) {
setTimeout(() => {
console.log('Step One Complete');
callback();
}, 1000);
}
function stepTwo(callback) {
setTimeout(() => {
console.log('Step Two Complete');
callback();
}, 800);
}
function stepThree() {
setTimeout(() => {
console.log('Step Three Complete');
}, 500);
}
// Nested Callbacks - Callback Hell
stepOne(() => {
stepTwo(() => {
stepThree();
});
});
Callback hell, also known as "Pyramid of Doom," is a situation where multiple nested callbacks make the code difficult to read and maintain. This often happens when dealing with complex asynchronous operations.
Top comments (0)