DEV Community

Saravanan s
Saravanan s

Posted on

Synchronous, Asynchronous, Callback Hell, and Promises in JavaScript

 Synchronous
In JavaScript, "synchronous" refers to the execution model where code runs in a sequential, blocking manner. This means that each operation must complete its execution before the next operation can begin.

Example code

console.log(1)
console.log(2)
console.log(3)
output print:
1
2
3
Enter fullscreen mode Exit fullscreen mode

Asynchronous

  Asynchronous programming in JavaScript allows operations to run independently without blocking the main execution thread.
Enter fullscreen mode Exit fullscreen mode

Example

console.log(1)

setTimeout(()=>{
console.log(2)
},2000)//here 2000 is (after 2 seconds)
console.log(3)
output print:
1
3
2(after 2 seconds)
Enter fullscreen mode Exit fullscreen mode

Callback hell

 Callback Hell Explained with a Real-Life Example Imagine you are building a software project. The process usually goes like this:
Enter fullscreen mode Exit fullscreen mode

Analysis → Gather requirements

Plan → Create a roadmap

Design → Decide how it should look/work

Develop → Write the code

Tester → Test the application

Deployment → Release the app

Here Problem: Callback hell makes code messy, hard to debug, and less readable.

Example

setTimeout(() => {
            console.log("Analysis");
            setTimeout(() => {
                console.log("Planing");
                setTimeout(() => {
                    console.log("Design");
                    setTimeout(() => {
                        console.log("Developer");
                            setTimeout(() => {
                            console.log("Testing");
                            setTimeout(() => {
                                console.log("Deployement");

                            },1000);

                        }, 1000);
                    }, 1000);

                }, 1000);
            }, 1000);
        }, 1000);
Enter fullscreen mode Exit fullscreen mode

Promises

  We use the Promise its help to the code readability is easy inside the function execution.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)