JavaScript
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
JAVASCRIPT
1function makeSandwich() {2 let bread = getBread(); // Must complete before moving on3 let cheese = getCheese(); // Waits for bread first4 let sandwich = bread + cheese;5 return sandwich;6}
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
JAVASCRIPT
1async function orderFood() {2 console.log('Ordering food...');34 try {5 // await lets us wait for the promise to resolve6 const food = await fetch(7 'https://api.restaurant.com/order'8 );9 console.log('Food has arrived!');10 return food;11 } catch (error) {12 console.log('Error ordering food:', error);13 }14}1516// This code runs while food is being ordered17console.log('Doing other things while waiting for food...');
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.
What is the difference between async and defer in JavaScript?What is the difference between == and === in JavaScript?What is difference between stopPropagation() and stopImmediatePropagation()?What are the key differences between var, let, and const in JavaScript?What is the difference between XMLHttpRequest and fetch?What is the difference between dot notation and bracket notation?