DEV Community

Sathish K
Sathish K

Posted on

Synchronization,Asynchronization,Callback hell and Promise in Java Script.

What is the Synchronization ?
In JavaScript, Synchronization is the single-threaded,meaning it the executes the one command at a time in order of the code.
Each statement code run one after another.

console.log("1");
console.log("2");
console.log("3");
Enter fullscreen mode Exit fullscreen mode

Output
1
2
3

What is the Asynchronization ?
Asynchronization in JavaScript refers to the ability of JavaScript to handle tasks that may take some time to complete (like fetching data from an API, reading a file, or setting a timer) without blocking the execution of other code.

console.log("Start");
setTimeout(() => {
  console.log("Inside timeout");
}, 1000);
console.log("End");

Enter fullscreen mode Exit fullscreen mode

Output
Start.
End.
Inside timeout.

What is the Callback hell ?
Callback is refers the situation in javaScript multiple nested callback.
It is make the code is hard to read,understand and maintain.
It is a Pyramid of Doom structure.

 setTimeout(() => {
            console.log("Analysis");
            setTimeout(() => {
                console.log("Plan");
                setTimeout(() => {
                    console.log("Design");
                    setTimeout(() => {
                        console.log("Developer");
                        setTimeout(() => {
                            console.log("Testing");
                            setTimeout(() => {
                                console.log("Depolyment");

                            }, 1000)

                        }, 1000)

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

Output
Analysis
Plan
Design
Developer
Testing
Deployment

What is the promise ?
In JavaScript,Promise is a built-in object represents the eventual completion or failure of an asynchronous operation and its resulting the values.
Then the code is easily understand and code simplify.
It is a help as write clear code in asynchronous operation without "callback hell".
It is two method is resolve,reject.

function task(step,result){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    console.log(step);  
                    if(result){         //if and else condition//
                        reject();
                    }else{
                    resolve();
                }

                },1000);
            })
        }
        task("Analysis")
        .then(()=>task("Plan"))
        .then(()=>task("Design",true))
        .then(()=>task("Development"))
        .then(()=>task("Testing"))
        .then(()=>task("Deployment"))
        .catch(()=>console.log("Testing failed"))
        .finally(()=>console.log("Hello"))
Enter fullscreen mode Exit fullscreen mode

Output
Analysis
Plan
Design
Testing
Hello
Testing failed

Top comments (0)