Synchronous vs Asynchronous Code
Synchronous code waits for each line to finish before the next one starts. Asynchronous code starts a slow task, moves on, and handles the result when it arrives.
Synchronous Code
Code that runs one line at a time. Each line waits for the last to finish.
Synchronous code runs one line at a time. Each line waits for the one before it to finish. If a line asks for a file or a web page, the whole program stops and waits. This is easy to read, because things happen in the order they are written. It becomes a problem when a wait is long. A screen can freeze, or a server can stop answering other people.
Asynchronous Code
Code that starts a slow task and keeps going. It handles the result later.
Asynchronous code starts a slow task and moves on without waiting for it. When the task is done, the program comes back to handle the result. Slow tasks are things like downloads, database calls and timers. This keeps a screen working and lets a server serve many people at once. Callbacks, promises and async/await are the tools for writing it.
In one line
- Synchronous Code
- Code that runs one line at a time. Each line waits for the last to finish.
- Asynchronous Code
- Code that starts a slow task and keeps going. It handles the result later.