This content originally appeared on DEV Community and was authored by Arika O
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
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
This content originally appeared on DEV Community and was authored by Arika O
Arika O | Sciencx (2021-06-07T20:23:17+00:00) Javascript – Introducing async code. Retrieved from https://www.scien.cx/2021/06/07/javascript-introducing-async-code/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.