Table of contents
No headings in the article.
CallBacks(ES5)?
Callback refers to a function passed as an argument to another function. It helps in asynchronous programming. Let's understand it using a real-life example.Sample Code:-
function display(sum)
{
document.getElementById("display-window").innerHTML=sum;
}
function calculateSum(num1,num2,myCallBack)
{
let sum=num1+num2;
myCallBack(sum);
}
calculateSum(10,12,display); //Never use () after function name if it is being passed as an argument.
Output:- 22
Problem with Callback Functions
The nesting of callback functions results in a callback hell or pyramid of doom as the function over-complicates with each new callback function. For Example:-What's the solution?
Breaking the nested callbacks into standalone functions that don't have deep-nesting is a primary solution to this, but the problem that arises is that it makes it difficult to read and follow every function.
Promises
The Promise is an agreement between the executor function and where its return value is going to be used. It returns a value only when it gets settled(either resolved to produce some value or rejected to produce an error). This helps in multiple ways like while calling web-APIs etc.Sample Code:-
let promise=new Promise((resolve,reject)=>{resolve("Completed");});
promise.then(result=>console.log(result));
Output:- Completed
Problem with Promises?
The only limitation of using promises is that the chain of chaining promises cannot be broken.What's the solution?
ASYNC/AWAIT
Async/Await came in ES2017 which makes the code look like it's synchronous but actually it is asynchronous and non-blocking. These have a higher level of abstraction over promises i.e. they are built on promises.Sample Code:-
const doSomethingAsync = () => {
return new Promise(resolve =>
{
resolve('Where?');
});
};
async function doSomething(){
console.log(await doSomethingAsync());
}
console.log("Let us");
doSomething();
console.log("go somewhere");
Output:- Let us
go somewhere
Where?
Await waits for the reply from doSomethingAsync() function and after it produces some value it is returned to doSomething() function and is printed at the last after the stack gets empty i.e all the console.log() commands are finished producing the output.
That's all folks! I hope it would have cleared the evolution journey from callbacks to async/await. Do let me know if I could add more to this. Bye👋👋.