Junior
What is the difference between synchronous and asynchronous code?
sobes.tech AI
Answer from AI
Synchronous code executes tasks sequentially, waiting for each to complete before moving to the next.
Asynchronous code allows tasks to run in the background without blocking the main execution thread and reacts to their completion when it occurs.
Main differences:
| Characteristic | Synchronous code | Asynchronous code |
|---|---|---|
| Blocking | Blocks the execution thread | Does not block the execution thread |
| Execution | Sequential | Parallel (in the context of non-blocking UI) |
| Waiting | Waits for the operation to finish | Does not wait, continues execution |
| Application | Simple operations that do not require waiting | Network requests, file operations, timers |
Example of synchronous (blocking) code:
// Request will block execution until response is received
const response = doSynchronousRequest('https://api.example.com/data');
console.log(response);
console.log('This line executes after receiving the response.');
Example of asynchronous (non-blocking) code:
// Request runs in the background
doAsynchronousRequest('https://api.example.com/data', (response) => {
console.log(response); // This code runs upon receiving the response
});
console.log('This line runs immediately, without waiting for the response.');