Understanding Synchronous, Asynchronous, Callbacks, Promises, and Async-Await in JavaScript
Synchronous vs Asynchronous
In JavaScript, code execution can be categorized into two main types: synchronous and asynchronous.
- Synchronous: Code runs in order, one statement at a time.
- Asynchronous: Code can run in parallel. If an instruction takes time, other instructions can continue to run simultaneously.
setTimeout
in JavaScript
The set Timeout
function is used to execute a function after a specified time interval. For example:
// Using a regular function
setTimeout(function hello() {
console.log("Hello");
}, 2000);
// Using an arrow function
setTimeout(() => {
console.log("Hello");
}, 2000);
Callbacks
A callback is a function passed as a parameter to another function. For instance, consider creating a calculator:
function sum(a, b) {
console.log(a + b);
}
function calculator(a, b, sumCallback) {
sumCallback(a, b);
}
calculator(1, 2, sum); // Output: 3
Callback Hell
Callback hell occurs when there are nested callbacks, making the code hard to understand. For example:
getData(1, () => {
console.log("Getting data 2...");
getData(2, () => {
console.log("Getting data 3...");
getData(3, () => {
console.log("Getting data 4...");
getData(4);
});
});
});
Promises
To mitigate callback hell, promises were introduced. A promise represents the eventual completion or failure of an asynchronous operation.
function getData(dataId, getNextData) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Data", dataId);
resolve("success");
if (getNextData) {
getNextData();
}
}, 2000);
});
}
Promises have three states: pending, fulfilled, and rejected.
Using Promises with .then()
and .catch()
getData(1)
.then((res) => {
return getData(2);
})
.then((res) => {
return getData(3);
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
Async-Await
Async-Await is a syntactic sugar for working with promises, making asynchronous code more readable.
async function getAllData() {
console.log("Getting data 1...");
await getData(1);
console.log("Getting data 2...");
await getData(2);
console.log("Getting data 3...");
await getData(3);
}
In summary, understanding the concepts of synchronous, asynchronous, callbacks, promises, and async-await is crucial for writing efficient and maintainable JavaScript code. These tools provide different ways to handle asynchronous operations, each with its own advantages and use cases.
Thanks for reading I learned this concept from