Synchronous functions execute immediately and block further code execution until they complete. Asynchronous functions start execution but don’t block the code — they complete later when the result is ready. Promise and async/await are used to work with asynchronous operations.
// Synchronous function
function syncFunc() {
console.log('Synchronous function');
return 'done';
}
// Asynchronous function with Promise
function asyncFunc() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Asynchronous function');
resolve('done');
}, 1000);
});
}
// Usage
syncFunc(); // Executes immediately
asyncFunc().then(result => console.log(result)); // Starts execution, but continues code
console.log('Code continues to run'); // Executes immediately
// After 1 second: 'Asynchronous function'
// Then: 'done'The difference between synchronous and asynchronous functions is like the difference between buying coffee at a café and ordering food for delivery. At a café you wait while they make your drink (synchronously), but at a restaurant you order food and continue doing things while the food is being prepared (asynchronously)! ☕
In modern JavaScript, Promise and async/await are used to work with asynchronous operations, making code more readable and easier to work with.
Synchronous functions are regular functions that execute immediately and block further code execution until they complete:
function syncTask() {
console.log('Start');
// Executes immediately
console.log('End');
}
syncTask();
console.log('This executes after syncTask');Asynchronous functions are functions that start execution but don’t block the code. They complete later when the result is ready:
function asyncTask() {
console.log('Start');
setTimeout(() => {
console.log('Completion after 1 second');
}, 1000);
console.log('Function completed (but not the task!)');
}
asyncTask();
console.log('This executes immediately after asyncTask starts');// Synchronously
function sync() {
console.log('1');
console.log('2');
console.log('3');
}
// Asynchronously
function async() {
console.log('A');
setTimeout(() => console.log('C'), 0);
console.log('B');
}
sync(); // Output: 1, 2, 3
async(); // Output: A, B, C// Synchronous function blocks everything
function syncDelay() {
const start = Date.now();
while (Date.now() - start < 3000) {
// Useless 3-second delay
}
console.log('Synchronous delay completed');
}
console.log('Start');
syncDelay(); // Wait 3 seconds
console.log('This appears only after 3 seconds');
// Asynchronous function doesn't block
function asyncDelay() {
setTimeout(() => {
console.log('Asynchronous delay completed');
}, 3000);
}
console.log('Start');
asyncDelay(); // Don't wait
console.log('This appears immediately');// Regular math operations
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
const sum = add(2, 3); // 5 (immediately)
const product = multiply(4, 5); // 20 (immediately)// Working with network
function fetchData(callback) {
console.log('Requesting data...');
setTimeout(() => {
callback('Data received');
}, 2000);
}
fetchData((data) => {
console.log(data);
});
console.log('Code continues to run');// For fast operations
function calculateTax(price) {
return price * 0.2;
}
function formatName(first, last) {
return first + ' ' + last;
}// For long operations
function loadUserData(userId, callback) {
// Simulating server request
setTimeout(() => {
callback({ id: userId, name: 'User ' + userId });
}, 1000);
}A Promise is an object representing the result of an asynchronous operation. A Promise has three states:
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
// Using Promise
myPromise.then(result => {
console.log(result); // 'Data received'
});async/await is syntactic sugar for working with Promises, making code more readable:
// Function with async returns Promise
async function fetchData() {
return 'Data';
}
// Using await instead of .then()
async function getData() {
const data = await fetchData(); // Wait for result
console.log(data); // 'Data'
}
getData();// ❌ Error — expecting result from asynchronous function
function asyncOperation() {
let result;
setTimeout(() => {
result = 'done';
}, 1000);
return result; // undefined!
}
const data = asyncOperation();
console.log(data); // undefined
// ✅ Correctly — using callback
function asyncOperationCorrect(callback) {
setTimeout(() => {
callback('done');
}, 1000);
}
asyncOperationCorrect((data) => {
console.log(data); // 'done'
});console.log('1');
setTimeout(() => {
console.log('2');
}, 0);
console.log('3');
// Output: 1, 3, 2 (not 1, 2, 3!)Understanding the difference helps write more efficient code and avoid errors with execution order! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪