Begineer: Synchronous vs Asynchronous Programming

maxwiggedal

Max Wiggedal

Posted on July 25, 2023

Begineer: Synchronous vs Asynchronous Programming

Synchronous Programming

Synchronous programming is perfect for when you have tasks that you know are non-time consuming and will simply run one after the other. Each task has to fully finish executing before the next task is started when using synchronous programming. You can look at it as a queue, first task that enters the queue fully executes and then the next task in the queue repeats the same process until the queue is empty.

When utilizing synchronous programming you can easily predict the order in which each task will execute. However this can be very slow for certain tasks such as making multiple network requests or I/O operations such as reading from a file or writing to a file. This is because each task has to finish running before it continues.

Asynchronous Programming

This is where Asynchronous programming comes into the picture. It allows you to offload time-consuming tasks onto another thread which means the code being executed on the main thread will not completely freeze in order to wait for our time-consuming code to execute.

In comparison to synchronous programming, asynchronous programming allows you to execute time-consuming tasks and return the result whenever it is ready without blocking other code from executing.

Example Difference

While JavaScript itself does not use threads, because it uses a model called the "Event Loop" it can still be used to demonstrate the difference between synchronous and asynchronous with the use of promises.

Synchronous

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

console.log("Sync: Hello"); // This will run instantly
await sleep(5000); // This will block the execution of any code until 5 seconds have passed
console.log("Sync: World!"); // This will run after 5 seconds
Enter fullscreen mode Exit fullscreen mode

Asynchronous

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

console.log("Async: Hello"); // This will run instantly
sleep(5000).then(() => console.log("Async: I am late :(")); // This will run after 5 seconds but will not block code execution
console.log("Async: World!"); // This will run instantly
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
maxwiggedal
Max Wiggedal

Posted on July 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related