DEV Community

John Samuel Obinna
John Samuel Obinna

Posted on

Asynchronous JavaScript for Newbies

When writing JavaScript we frequently deal with Asynchronous code which can be confusing for us as newbies. Before we jump into Asynchronous JavaScript lets talk a little about Synchronous Code.

What is Synchronous Code?

Synchronous Code runs on a single thread. 1 Action is completed before moving to the next.

 thread -

Enter fullscreen mode Exit fullscreen mode

Asynchronous Code

Unlike Synchronous code, asynchronous code runs now and finishes later.
From the illustration below, as you can see, the fn2 line was not finished but was completed after fn6 has been executed.

 thread -                                                Separate thread outside you code.
          |                                             /
          V                                            /
          Start|fn1<--------A---------->|Finish       /
          Start|fn3<--------C---------->|Finish       |
          Start|fn4<--------D---------->|Finish       V 
          Start|fn5<--------E---------->|Finish       | 
          Start|fn6<--------F---------->|Finish       V  
      Callback |fn2<--------B---------->|<------------|                                               

Enter fullscreen mode Exit fullscreen mode

Note that JavaScript is single-threaded, only to code you write but Requests made from your code are handed over to a separate thread. Let's say an Api call for example. Hold it, i know what you are thinking; What's a 'Callback'? Don't worry next we're going to discuss 'Callback'.

What is a Callback?

A callback is a function passed into another function as an argument, which is then invoked inside the out function to complete some kind of action.

function Callback(){
 alert("You called Me");


// You called Me

Enter fullscreen mode Exit fullscreen mode

This is a Synchronous callback, next we're going to talk about

-Asynchronous callback.
-Callback Hell.
-Ajax Requests.

Discussion (5)

adroitcoder profile image
John Samuel Obinna Author

I'm glad you liked it. Using
-Asynchronous callback.
-Callback Hell.
-Ajax Requests.
will be up soon.

jidelambo profile image
Jide Lambo

Where you able to write a follow-up article? This was helpful.

pedrofumero profile image
Pedro Fumero

Good article! I'll be waiting for the next parts! :)