Understanding Asynchronous JavaScript — Callback, Promise and Async-Await
By: Sohail Pathan
Tags: JavaScript, Asynchronous

While developing a dynamic web application, one of the major tasks is being able to make dozen of AJAX calls.

JavaScript is one of the synchronous and single thread language, It means it cannot create multiple threads automatically and execute from top to bottom one by one in parallel.

function doMultiply(){

val a = 2

val b = 5

val c = a * b

console.log(c)}

doMultiply();

But again, the question arises is How could it do this with asynchronous programming model in production level?

So here, the answer was in its Asynchronous environment. The Web browser provides a way to do it by providing a callback function, promise, and Async-Await that can handle this kind of functionality.

So let’s understand and see what inside in it.

What is a Callback?

Basically, A callback is a function that is to be executed after an earlier function has finished executing its task. Hence the name refers ‘call back’.

So, Callback functions are derived from a programming paradigm known as functional level programming. When a function simply accepts another function as an argument, this contained function is known as a callback function. Use of callback functions is a core functional programming concept, and you can find them in most JavaScript code. Let’s look at the basic example:

let add = function(a,b){

return a+b;

}; let sub = function(a,b){

return a-b;

}; let calculate = function(first,second,callback){

return callback(first,second);

}; console.log(calculate(2,1,sub));

console.log(calculate(2,5,add));

Here we got the output as,

>> 1

>> 7

So here we see the use of a callback, We can create any function and pass it into another function as an argument.

What is Promise?

In real life, we make promises to assure that one particular thing will definitely happen.

As same, In JavaScript, it represents the result of an asynchronous operation.

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

Once a promise is fulfilled or rejected, it is immutable means it will not change again.

Lets took an example of promise:

let gotoSchool = function(){

return new Promise(function(resolve,reject){

resolve('I went to school');

});

}; let ComeBackToHome = function(message){

return new Promise(function(resolve,reject){

resolve(message + 'I came back from school');

});

}; let doLunch = function(message){

return new Promise(function(resolve,reject){

resolve(message + 'I did lunch');

});

}; gotoSchool().then(function(result){

return ComeBackToHome(result);

}).then(function(result){

return doLunch(result);

}).then(function(result){

console.log('finish' + result);

})

Here we got the output as,

I went to school I came back from school I did lunch finish

So here we see, Our all the functions are expecting to resolve and execting task simultaneously.

What is Async-Await?

While working with Promise in JavaScript, We have a special syntax to work in a more comfortable manner to implement the asynchronous model. Async/await functions, is a new addition with ES2017 (ES8), help us even more in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.

Alright so let see what async/await actually is, As the name suggests there is Async you need to weight. Because JavaScript is non-blocking by default, it means it doesn’t wait for sync.

Async declaration defines an asynchronous function, which returns an AsyncFunction object.

Await declaration causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment.

Understand it by an example:

const asyncHello = async () => 'Hello';

const promiseHello = () => new Promise(((resolve) => {

resolve('Hello how are you?');

}) ,30000);

asyncHello().then(result => console.log(result));

promiseHello().then(result => console.log(result));

We got the output as:

>>Hello

//After waiting

>>Hello, How are You?

That’s it!

In conclusion, I would like to say that we understand how JavaScript achives the asynchronous programming models in production level.