Asynchronous JavaScript for Newbies
John Samuel Obinna
Posted on April 26, 2018
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
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---------->|<------------|
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
This is a Synchronous callback, next we're going to talk about
-Asynchronous callback.
-Callback Hell.
-Ajax Requests.
-Promises.
-Generators.
Posted on April 26, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.