What is difference between sync and async function?

JavaScript

async vs sync function

Synchronous Functions:

  • Execute code line by line, in sequence
  • Each operation must complete before moving to the next one
  • Block the execution of other code while running
function makeSandwich() {
let bread = getBread(); // Must complete before moving on
let cheese = getCheese(); // Waits for bread first
let sandwich = bread + cheese;
return sandwich;
}

Asynchronous Functions:

  • Allow other code to run while waiting for operations to complete
  • Don't block execution
  • Often used for operations that might take time (API calls, file operations, etc.)
  • Use keywords like async and await, or work with Promises
async function orderFood() {
console.log('Ordering food...');

try {
// await lets us wait for the promise to resolve
const food = await fetch(
'https://api.restaurant.com/order'
);
console.log('Food has arrived!');
return food;
} catch (error) {
console.log('Error ordering food:', error);
}
}

// This code runs while food is being ordered
console.log('Doing other things while waiting for food...');
00:00

Table of Contents