Promises ( PART 1 ) - Asychronous Code & Callbacks !


What do you think a Promise is ?

It's not that Complicated . In this blog I'll try and break it to you guys in very simple terms what are these and why are they used ! I have divided this Topic into two Parts & We'll go step by step from the basics.

Promises are one of the ways we can deal with asynchronous operations in JavaScript
But before we talk about promises , Let's try and understand what asynchronous javascript is !


Synchronous & Asynchronous

Now , Have a look at the code below ! We can see that all the code is executed line by line in a Synchronous manner. This is the behavior we expect when we write any code.

See the Pen Async,Sync by Simran N Wasnik (@Sam11298) on CodePen.

Well, Have a look at the below code and try to think about the expected result. Okay , If you have made your mind about the result . Rerun the code to check !

See the Pen JjXaONL by Simran N Wasnik (@Sam11298) on CodePen.

We can see that in this case 1 & 3 were printed first and then the 2nd element .

This is something called Asynchronous code where JS  didn't wait for the value of  2nd element and instead went on and executed the 3rd element and then came back to the second . Note that the setTimeout function we used here is just to stimulate a more real-world Asynchronous function like doing a AJAX request to fetch data from an API.

After Learning how Async code works , Let's take a look at Callbacks which is a more traditional way of dealing with Async functions.


Callback

A callback function is usually used as a parameter to another function.
The function that receives the callback function as a parameter is normally fetching data from a database, downloading a file, making an API request, or completing some other task that could block the code thread for a notable amount of time.

Imagine, for example, that you are going to download an image. The download takes about 2 seconds, and you don't want your program to stop on this line of execution as you wait for the download to finish. A callback allows you to keep running other functions and "call back" the image after the download is complete.

Let's look at an example using the setTimeout as a callback function .
Copy the code below and use any code editor or console to see how it works !

function getStudentData (){

    setTimeout(()=>{
        const studentid = [523,32,232,323];
        console.log('List of IDs :',studentid);

        setTimeout((id)=>{
            const gradeofStudent  = {grade:'K4',id:'32'};
            console.log('Grade of the student:',gradeofStudent.grade);


        },1500,studentid[2])	


    },1500)
}
getStudentData();

Let's say we want to fetch the grade of a particular student using his ID. Assume we call an API (using setTimeout) for fetching the student ID's .

The first API gives you the list of ID's . Now we want to call an other API and pass a particular student ID to get his grade.So the second timeout does it for us !

Till here we are good !

Look at the below code ! This is when things get a little confusing .Some functions that use asynchronous calls can end badly, like this one:  Copy the code and use any code editor or console. Now , Having the grade of the student . We even want his/her name . Therefore , We make an other call to an API sending the grade as parameter to fetch the name .

function getStudentData (){

    setTimeout(()=>{
        const studentid = [523,32,232,323];
        console.log('List of IDs :',studentid);

        setTimeout((id)=>{
            const gradeofStudent  = {grade:'K4',id:'32'};
            console.log('Grade of the student :',gradeofStudent.grade);

            setTimeout((e)=>{
                const nameofStudent = {name:'Simran',grade:'K4',id:'32'};
                console.log( ` ${nameofStudent.name} is in Grade ${e.grade}with 
id ${e.id}`);

            },1500,gradeofStudent)


        },1500,studentid[2])	


    },1500)
}
getStudentData();

Well, Having to do this multiple times increasing the levels can be complicating. As we can see, this code is hard to understand and maintain, and it isn't scalable. This is what we call callback hell .

What do We do Now !

Don't worry Promises has got your back !

In the next Chapter , We' ll talk about Promises and Async Awaits and how can they help us !

Link to the next Chapter