Asynchronous programming in javascript

Let us take a look at the below example. We are trying to print family members by an order which occur asynchronously.



function printfamilyOrder(param){
	setTimeout( () => {
		console.log(param);
	}, Math.random()*100);
}

printfamilyOrder('grand father');
printfamilyOrder('father');
printfamilyOrder('son');

Random output:

father
grandfather
son

The output is not as expected and we achieve the order by async programming, using a callback, promise and async/await mechanism.

Callback

callback functions are internal functions that are passed as a parameter to a function and get called after execution on the external function.

Example:

function printfamilyOrder(val, cb){
	setTimeout( () => {
		console.log(val);
		cb();
	}, Math.random()*100)
}

printfamilyOrder('grand father', () => { printfamilyOrder('father', () => { printfamilyOrder('son') })});

Output:

grandfather
father
son
promise

 

function printfamilyOrder(val, cb){
   return new Promise( (resolve,reject) => {
    setTimeout( () => {
     console.log(val);
     resolve();
    }, Math.random()*100)
   })
}

printfamilyOrder('grand father')
.then( () => { printfamilyOrder('father')} )
.then( () => { printfamilyOrder('son')} );

Output:

grandfather
father
son
Async/Await

Async/Await is a sugar coat on top of promises that help in writing promises a much cleaner way.

 

function printfamilyOrder(val, cb){
 return new Promise( (resolve,reject) => {
  setTimeout( () => {
  console.log(val);
  resolve();
  }, Math.random()*100)
 })
}

await printfamilyOrder('grand father')
await printfamilyOrder('father')
await printfamilyOrder('son')

Output:

grandfather
father
son