DEV Community

LAKSHMI G
LAKSHMI G

Posted on

Synchronous, Asynchronous, Callback Hell, and Promises in JavaScript

Synchronous

  • synchronous execution task run step by step(one after another) ,each step waits for the previous one to finish.

Example:

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

Asynchronous

  • asynchronous execution does't wait.It can run tasks in the background(like fetch data) and continue with other work

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:

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

Promise

  • We use the Promise its help to the code readability is easy inside the function execution.
<script)>
function task((step,result){
return new promise(resolve,reject)=>{
setTimeout(()=>{
console.log(step)
 if (result) {
                        reject();
                    } else{
                        resolve()
                    }



                }, 1000);
            })
        };

 task("Analysis")
            .then(() => task("plan"))
            .then(() => task("Design", true))
            .then(() => task("Development"))
            .then(() => task("Testing", true))
            .then(() => task("Deployment"))
            .catch(() => console.log("Testing failed"))
            .finally(() => console.log("hello"))
</script)>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)