DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Synchronous ,Asynchronous , Promise in JS

Synchronous JavaScript :

  • Code runs line by line, and each line waits for the previous one to finish.
console.log("First");
console.log("Second");
console.log("Third");

Output :
First
Second
Third

Enter fullscreen mode Exit fullscreen mode
  • If a single line of code takes a long time (like a huge loop or a complex calculation), it blocks the rest of the program from running.
function slowTask(){
        for(let i=1; i<999999999; i++){

        }
}
console.log("First");
slowTask();
console.log("Third");

Output :
First 
Third
Enter fullscreen mode Exit fullscreen mode

Asynchronous JavaScript :

  • Asynchronous code allows a program to start a long-running task and continue with others before that task finishes.
  • Code doesn't wait — it moves on and comes back when the task is done.So the page wouldn't freeze.

Used in:

  • Fetching data from an API.
  • Reading a file
  • Database queries
  • Timers
console.log("First");
setTimeout(() => {
        console.log("Async task");
}, 2000);
console.log("Third");

Output :
First
Third
Async task //Appears after 2 seconds
Enter fullscreen mode Exit fullscreen mode

Promise JavaScript :

  • JavaScript Promises were created to make asynchronous JavaScript easier to use.
  • A Promise object represents the completion or failure of an asynchronous operation.
  • A Promise can be in one of three exclusive states.
    • pending : The initial state; the operation has started but is neither fulfilled nor rejected.
    • fulfilled : The operation completed successfully, and a value is available.
    • rejected : The operation failed, and a reason (error) is available.

Why Promise ?

  • When callbacks are nested inside callbacks deeply, it becomes hard to read and hard to maintain.
setTimeout(() => {
        console.log("Analysis");
        setTimeout(() => {
                console.log("Design");
                setTimeout(() => {
                        console.log("Development")
                        setTimeout(() => {
                                console.log("Testing")
                                setTimeout(() => {
                                        console.log("Deployment")
                                }
                                        , 1000)
                        }, 3000)

                }, 5000)
        }, 2000)

}, 4000);

Output : 
Analysis
Design
Development
Testing
Deployment
Enter fullscreen mode Exit fullscreen mode
  • The style above is called callback hell.
  • Promises let us write the same logic in a cleaner way.

Creating a Promise :

//ex : 1
function createPromise(type) {

        return new Promise((resolve, reject) => {
                if (type)
                        resolve("Task Completed");
                else
                        reject("Task Failed");
        })

};


createPromise(true).then((res) => { console.log(res) }).catch((err) => { console.log(err) })
createPromise(false).then((res) => { console.log(res) }).catch((err) => { console.log(err) })

Output : 
Task Completed
Task Failed


//--------------------------------------------------------------
//ex : 2
const createPromise =  new Promise((resolve, reject) => {
        let type = true;
                type? resolve("Task Completed"):reject("Task Failed")
        })

createPromise.then((res) => { console.log(res) }).catch((err) => { console.log(err) })

//------------------------------------------------------------
//ex : 3
function development(){

        const dev= new Promise((resolve, reject) => {

               resolve("Development Completed");
        })
        return dev

}

function testing(){

        const test = new Promise((resolve, reject) => {
               resolve("Testing Completed");
        })
        return test

}

development()
        .then((a)=>{
                console.log(a); 
                return testing()
        })
        .then((b)=> console.log(b));


Output : 
Development Completed
Testing Completed

//------------------------------------------------------------

//ex : 4
<body>

<p id="par"></p>

<script>

        let par = document.querySelector("p")

        function countDown(no) {

                const count = new Promise((resolve, reject) => {

                        par.innerText = no;
                        setTimeout(() => { resolve(); }, 1000)
                })
                return count;

        }

        countDown(3)
                .then(() => { return countDown(2) })
                .then(() => { return countDown(1) })
                .then(() => { return countDown("Good Morning") })

</script>
</body>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)