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 -
          |
          V    
          Start|Line1<---------A--------->|Finish
          Start|Line2<---------B--------->|Finish
          Start|Line3<---------C--------->|Finish


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|fn2<--------B-----------|-------------|
          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");
}

setTimeout(callback,300);

// 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.
-Promises.
-Generators.

Top comments (3)

Collapse
 
johnsamuelob profile image
John Samuel Obinna

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

Collapse
 
jidelambo profile image
Jide Lambo

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

Collapse
 
pedrofumero profile image
Pedro Fumero

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