Coding

Synchronous vs Asynchronous Programming: What's the Difference?

Synchronous code runs one step at a time and waits for each step to finish before starting the next. Asynchronous code starts a slow step, such as a download, and carries on with other work until the result arrives.

The two styles differ in what happens during a wait. In the first, everything stops. In the second, the program uses the time. The sections below define each term, compare them side by side, and show the same task written both ways in JavaScript and Python.

What is synchronous programming?

MDN describes a synchronous program as one where the browser steps through the code one line at a time, in the order it was written, and at each point waits for the line to finish its work before going on to the next. It has to, because each line depends on the work done in the lines before it.

The same idea applies to functions. MDN calls a function synchronous when the caller has to wait for the function to finish its work and return a value before the caller can continue. Most everyday code works this way: adding two numbers, formatting a string, looking up a key in a dictionary. These finish so quickly that waiting costs nothing.

What is asynchronous programming?

MDN's definition: asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once the task has finished, your program is presented with the result.

So an asynchronous call does not hand back the answer when you make the request. It hands back a placeholder (a Promise in JavaScript, a coroutine or task in Python, a Task in C#) and delivers the answer later. In the meantime the caller is free to do something else.

Synchronous vs asynchronous: the differences

SynchronousAsynchronous
Order of workOne step after another, in the order writtenA slow step is started, other work continues, the result is picked up later
During a slow callThe thread is blocked and nothing else on it runsControl returns to the caller, which can do other work
What a call returnsThe value itselfA placeholder for the value (Promise, coroutine, Task)
On a UI threadA slow call freezes the windowThe window keeps responding
Code complexityReads top to bottom, simple to followAdds await points and a second way to fail
Best forFast operations and calculationsWaiting on network, disk, databases and timers

Why blocking is the real problem

MDN illustrates the cost with a page that generates large prime numbers when you click a button. The click handler runs the calculation synchronously. MDN reports that while the function is running, the program is completely unresponsive: you can't type anything, click anything, or do anything else. The reason it gives is that the JavaScript program is single-threaded, so it can only do one thing at a time, and while it waits for a long synchronous call to return, it can't do anything else.

Desktop applications have the same trap. Microsoft's C# documentation explains that all UI-related activity usually shares one thread, so if any process is blocked in a synchronous application, all are blocked. The application stops responding, and you might conclude that it failed when instead it's just waiting.

The same task in both styles

Python's documentation has a small example that shows the difference in timing. The function say_after waits for a delay, then prints a word. Here it runs synchronously from the caller's point of view, with each await finishing before the next line starts:

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

Example output (the Python docs state the timestamps are illustrative):

started at 17:13:52
hello
world
finished at 17:13:55

The two waits add up to 3 seconds because the second call does not start until the first one is done. Now start both at once with asyncio.TaskGroup (available from Python 3.11):

async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(say_after(1, 'hello'))
        task2 = tg.create_task(say_after(2, 'world'))

        print(f"started at {time.strftime('%X')}")

    print(f"finished at {time.strftime('%X')}")

Example output:

started at 17:14:32
hello
world
finished at 17:14:34

Now the total is 2 seconds, the length of the longest wait, because the waits overlap. That overlap is the practical benefit of asynchronous code. Note that a plain await in a row is still sequential, so writing async and await does not by itself make anything concurrent. You have to start the tasks together.

A JavaScript example of the difference in order

In JavaScript the most visible difference is the order in which lines run:

async function fileSize(url) {
  const response = await fetch(url);
  const text = await response.text();
  return text.length;
}

fileSize("/data.txt").then(size => console.log(size));
console.log("this line prints first");

The last line prints before the size, because fileSize pauses at its first await and gives control back to the caller. With a synchronous version, the program would sit at the request and print the lines in the order they appear. For a closer look at promises, errors and running requests in parallel, see the JavaScript async/await guide.

Is asynchronous the same as multithreaded?

No. This is the most common mix-up. Asynchronous code avoids waiting idly. Multithreaded code runs on more than one thread. Microsoft's documentation says the async and await keywords don't cause extra threads to be created, and that an async method doesn't run on its own thread: it runs on the current synchronization context and uses time on the thread only when the method is active. It adds that you can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

The rule of thumb that follows: async helps when the program waits, and a thread or process helps when the program computes. The plain-English explanation of async covers the keywords in JavaScript, Python and C# in more detail.

When to use each

Keep code synchronous when the operation is fast or the next step cannot start without the result and nothing else needs the thread. Calculations, in-memory transformations and short scripts fall here. Simpler code is easier to read and debug.

Use asynchronous code when a step waits on something outside the processor. Microsoft lists web access, file work and image handling as typical areas, and calls asynchrony especially valuable for applications that access the UI thread. A command-line script that makes one request and exits gains little. A server handling many requests, or a window that must stay responsive, gains a lot.

Common mistakes when mixing the two

  • You get a Promise, coroutine or Task instead of a value. An asynchronous call returns a placeholder. Await it, or use .then() in JavaScript.
  • Python prints <coroutine object main at 0x...> and nothing runs. The Python docs note that simply calling a coroutine will not schedule it to be executed. Await it from another coroutine or start it with asyncio.run().
  • An async method has no await. Microsoft's docs say it then executes as a synchronous method does, despite the async modifier, and the compiler issues a warning.
  • The page still freezes after you made the function async. If the slow part is calculation, not waiting, async does not move it off the thread. Use a worker thread or a separate process.

Frequently asked questions

Is asynchronous code faster than synchronous code?
Not on its own. Asynchronous code lets a program do other work while it waits for something slow, such as a network response, so the total time for many waiting tasks can drop. It does not make a single calculation run faster, and for CPU-heavy work it gives no benefit.
Does asynchronous mean multithreaded?
No. Microsoft's C# documentation states that the async and await keywords do not cause extra threads to be created and that an async method does not run on its own thread. MDN describes JavaScript as single-threaded, and it still uses asynchronous code. Threads are one way to get parallel work. Async is a way to avoid idle waiting.
What does blocking mean?
A blocking call holds the current thread until it returns, so nothing else on that thread can run. A non-blocking call returns control to the caller right away and delivers its result later. Synchronous code is blocking by nature, which is why a slow call on a UI thread freezes the window.
Can one program use both synchronous and asynchronous code?
Yes, and most do. Microsoft's walkthrough of an async C# method calls an ordinary synchronous method, DoIndependentWork, while a web download is still in progress. Quick operations stay synchronous. Only the slow, waiting parts need to be asynchronous.

Sources