Hey there, awesome devs! ๐ Have you ever wondered why some JavaScript code runs instantly, while other parts take time to complete? That's because JavaScript can be asynchronous! ๐ญ
๐ญ What is Asynchronous JavaScript?
JavaScript is single-threaded, meaning it executes code line by line. But sometimes, you need to wait for things like:
- Fetching data from an API ๐ก
- Reading files from a disk ๐
- Waiting for a user action โณ
Instead of blocking execution, JavaScript allows these tasks to run asynchronously so other code can continue running.
๐ฅ Synchronous vs. Asynchronous Execution
Letโs compare synchronous and asynchronous code:
๐ข Synchronous Example:
console.log('Start');
for (let i = 0; i < 3; i++) {
console.log('Processing...');
}
console.log('End');
โ The code executes line by line, blocking the next step until the current one finishes.
๐ต Asynchronous Example:
console.log('Start');
setTimeout(() => {
console.log('Processing...');
}, 2000);
console.log('End');
โ
The setTimeout
function delays execution without blocking the next line.
๐ Callbacks: The Old Way
A callback function is a function passed as an argument that gets executed later.
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 2000);
}
console.log('Start');
fetchData((data) => {
console.log(data);
});
console.log('End');
โ But callbacks can get messy with nested functions โ leading to callback hell! ๐ฅ
๐ Promises: A Better Way
A Promise is an object that represents a future value.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
console.log('Start');
fetchData.then((data) => console.log(data));
console.log('End');
โ Promises improve readability and avoid deeply nested callbacks.
๐ Async/Await: The Best Way!
The async
and await
keywords make asynchronous code look synchronous.
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
}
async function start() {
console.log('Start');
const data = await fetchData();
console.log(data);
console.log('End');
}
start();
โ
await
pauses execution until the Promise resolves, making the code cleaner.
๐ When to Use Asynchronous JavaScript?
Use asynchronous code when:
- Fetching API data ๐
- Reading/Writing files ๐
- Handling user interactions ๐ฎ
- Running background tasks ๐
๐ฅ Final Thoughts
Mastering Asynchronous JavaScript is key to building fast and efficient applications! ๐
In the next article, weโll explore fs Promise Module โ stay tuned! ๐ฏ
If you found this blog helpful, make sure to follow me on GitHub ๐ github.com/sovannaro and drop a โญ. Your support keeps me motivated to create more awesome content! ๐
Happy coding! ๐ป๐ฅ
Top comments (0)