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
function makeSandwich() {let bread = getBread(); // Must complete before moving onlet cheese = getCheese(); // Waits for bread firstlet 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
javascript
async function orderFood() {console.log('Ordering food...');try {// await lets us wait for the promise to resolveconst 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 orderedconsole.log('Doing other things while waiting for food...');