Understanding Asynchronous JavaScript
Introduction
One of the
ideas in JavaScript that I think most beginners struggle with is asynchronous
programming. I struggled to understand it as well. It took some time for me to
finally grasp this notion, despite the fact that I saw a number of tutorials
and read a lot about it.
In order
to make asynchronous JavaScript easy to comprehend for novices, I will do my
best to describe it in this essay.
JavaScript
is a single-threaded programming language which means only one thing can happen
at a time. That is, the JavaScript engine can only process one statement at a
time in a single thread.
While the
single-threaded languages simplify writing code because you don’t have to worry
about the concurrency issues, this also means you can’t perform long operations
such as network access without blocking the main thread.
Imagine
requesting some data from an API. Depending upon the situation the server might
take some time to process the request while blocking the main thread making the
web page unresponsive.
To tackle
this, using asynchronous JavaScript (such as callbacks, promises, and
async/await), you can perform long network requests without blocking the main
thread.
So without
further ado, Let’s get started :)
let’s
first take a look at Synchronous before diving into Asynchronous JavaScript.
What
is Synchronous JavaScript and how does it Work?
In
synchronous operations tasks are performed one at a time and only when one is
completed, the following is unblocked.
Codes are
executed sequentially, that is one after the other, each waiting for the other
to be executed completely before it can execute the next in order. Synchronous
JavaScript executes codes from top to bottom.
Let’s look
at the example below to enable us understand better :
Here is
the result after the code executes:
From the
result, you can see that the JavaScript engine executes the code sequentially
beginning from the first line of code to the second.
This is
how synchronous JavaScript works, it executes the first line of code which in
this case is “Solomon” before it then goes down to execute the next line of
code or program.
I am sure
at this stage you understand how synchronous JavaScript works, so let’s dive
into the main reason for this article which is asynchronous JavaScript.
Now that
we have a basic knowledge of what synchronous JavaScript is, let’s simple dive
into the main topic of today.
What
is Asynchronous JavaScript And How Does Asynchronous JavaScript Work?
One can
describe asynchronous JavaScript to be the exact opposite of synchronous
JavaScript.
Here a
logic or programs are not executed sequentially or in an orderly manner but
instead, they are executed based on code that is ready to be executed at that
point in time.
Let’s take
a look at the example below to help us better understand this:
Unlike the
first example, the JavaScript engine won’t execute the code sequentially. Let’s
take a look at the result below:
As you can
see on the code above, we have a setTimeout function that logs
Hello while the second code logs Hello Samson and then the last logs Hello
Again! on the console.
The
JavaScript engine goes through the first function which is the setTimeout
function but its not able to execute it, and that is because it is set to
execute after 3 seconds therefore the JavaScript engine does not wait, instead,
it immediately moves to the second code and executes that, goes to the third
code executes it before executing the setTimeout function after 3 seconds.
This is a
typical example of how asynchronous JavaScript works, unlike the synchronous
JavaScript that must execute each code in an orderly manner.
Let’s look
at the ways of executing asynchronous JavaScript.
Methods
of executing asynchronous JavaScript
There are
three ways of writing asynchronous JavaScript code namely:
·
callback
·
promises
·
await/async
In this
article I will only be writing on callback and promises.
let’s
start with callback:
callback
So in
simple parlance, A callback is a function that we call inside another function.
It may or may not be executed asynchronously. Normally callback runs after the
parent function completes its operation.
“A
callback function is a function passed into another function as an argument,
which is then invoked inside the outer function to complete some kind of
routine or action.” MDN
Let’s see
an example below:
// execute
function getData(data, callback) {
setTimeout(()=> {
console.log("reading from the
database...");
callback({data: data});
}, 2000)
}
// display
getData(5, function(data){
console.log(data);
});
On the
execute block, getData() is a function that simulates getting
data from a database, the first argument is the data and the second argument
would be the callback which we want to run when we get back that data. For
quick simulation, we are going to be using the timeout function which will run
after a certain amount of time. On the display, the callback is
the function that is executed after the data, which is 5, in
this case, is fetched and the set time has elapsed in this case.
Here
callback is executed asynchronously.
Promises
Promises
are alternatives to a callback. It is basically an object which takes a
callback and executes it asynchronously. A promise can either resolve (be
successful) or reject (some error occurred), pending: still executing.
A promise
is considered easier to use and maintain than callbacks, mostly because the
syntax is much simpler.
const promise = new Promise((resolve, reject) => {
// perform async operation here if () {
// everything turned out fine
resolve("response
worked!");
}
else {
reject(new Error("something
went wrong"));
}
});promise.then((result) => {
console.log(result); //
"response worked!"
}).catch((err) => {
console.log(err); // "something
went wrong"
});
As we can
see, .then() takes two arguments, one for success, one for
failure (or fulfill and reject, in promises-parlance).
The .catch() block
helps you handle any error that occurs in the .then() chain.
Also, you
may observe that a promise did not remove the use of callbacks, but it made the
chaining of functions straightforward and simplified the code, making it much
easier to read.
Conclusion
Although we've just scratched the surface of asynchronous activities in JavaScript, it's a good idea to understand the concepts of Callbacks and Promises as they will serve as a solid foundation for dealing with asynchronous actions, particularly when making API requests and handling events.
Happy programming!
Resources
Callback & Promises: A basic Introduction
Understanding Asynchronous JavaScript
Learn How Asynchronous JavaScript Works
The Odin Project empowers aspiring web developers to learn together for
free
Understanding Asynchronous JavaScript | By Gabrielle Davidson | Tealfeed
paraphrasing tool: rewrite any paragraph or article. Try 7 different rewriting modes.
Comments
Post a Comment