DEV Community

Cover image for Javascript - Introducing async code

Javascript - Introducing async code

Arika O
・2 min read

In the last article, we saw that at its core, Javascript is synchronous (statements in our code are executed one after the other and we need to wait for a statement to finish execution before moving to the next) and the behaviour of its functions is blocking (if we have an expensive method, until that method doesn't return, no other block of code can run).

When having complex programs, this behaviour will create problems (in the context of browsers, this means that our browser will be stuck until the blocking function finishes execution). Fortunately, there are ways to fix this by writing asynchronous code.

Asynchronous code is code that allows a program to ask that a task be performed at the same time with the original task/ taks (so, multiple tasks at the same time). Stopping the execution until the first task returns is not necessary and when the secondary task is completed, the main task is somehow notified. This way it will know the works is done and if there's a result or a failure, it will know about that also.

In Javascript, we can implement an asynchronous behaviour in a number of ways by using:

  • callback functions
  • timeouts and intervals
  • promises
  • async/ await (which is just syntactic sugar on top of promises)

The main benefits we gain from using asynchronous programming is that our applications will have improved performance and responsiveness. For example, async programming will help deliver a responsive UI to the users while running a computationally expensive operation, at the same time.

In the next article we'll talk about callbacks and how we can use them to write asynchronous code.

*Image sources: James Harrison/ @jstrippa on Unsplash

Discussion (3)

daredia profile image
Shehzad Daredia

Thanks for sharing! Would love to read your subsequent posts in this series ASAP as I'm preparing for interviews - happy to provide feedback on drafts :)

benjaminv profile image

Thanks for sharing Marika. Please continue with this great blog it clarifies a lot for juniors like I am.

arikaturika profile image
Arika O Author

Thank you for the comment, I hope these text help :).