Synchronous vs. Asynchronous Programs

Differentiate between synchronous and asynchronous programs and learn to start task processes.

Synchronous code

By default, when we run some code in Elixir, we have to wait for it to complete. We get the result as soon as the code finishes but cannot do anything in the meantime. The code is executed synchronously and is sometimes called blocking code.

Asynchronous code

The opposite of this is running code asynchronously. In this case, we ask the programming runtime to run the code but carry on with the rest of the program. Asynchronous code runs in the background because the application keeps running as if nothing happened. Eventually, we can retrieve the result when the asynchronous code finishes. Since asynchronous code doesn’t block the program’s main execution, it is called non-blocking code. Asynchronous code is also concurrent since it enables us to continue doing other work. The figure below illustrates the difference between synchronous and asynchronous code in a bread-making program:

Get hands-on with 1200+ tech skills courses.