DEV Community

Sivakumar Mathiyalagan
Sivakumar Mathiyalagan

Posted on

Promises - JavaScript

what is promises in Javascript?

JavaScript is synchronous by default, which means code executes in a linear, line-by-line manner. Each statement waits for the previous statement to finish before executing.

However, some operations like:

API calls
Database queries
File reading
Timers (setTimeout)

take time to complete. If JavaScript waited for these operations synchronously, the entire program would pause and become slow or unresponsive.

To avoid blocking execution, JavaScript supports asynchronous programming.

A Promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises allow JavaScript to continue executing other code while waiting for long-running tasks to finish.

Promises have three states:

Pending = operation is still running
Resolved = operation completed successfully
Rejected = operation failed

Why Promises?

Callback functions also help perform asynchronous operations in JavaScript.

A callback function is a function passed as an argument to another function and executed later, usually after an asynchronous task completes.

Before Promises were introduced, callbacks were commonly used for handling asynchronous tasks

However, when multiple asynchronous operations depend on each other, callbacks become deeply nested, leading to a problem called Callback Hell.

function analyse(callback) {
    setTimeout(() => {
        console.log("done analysis");
        callback();
    }, 2000);
}

function design(callback) {
    setTimeout(() => {
        console.log("done design");
        callback();
    }, 1000);
}

function develop(callback) {
    setTimeout(() => {
        console.log("done development");
        callback();
    }, 3000);
}

function test(callback) {
    setTimeout(() => {
        console.log("done testing");
        callback();
    }, 2000);
}

function deploy(callback) {
    setTimeout(() => {
        console.log("done deployment");
        callback();
    }, 1000);
}
Enter fullscreen mode Exit fullscreen mode

to execute in order this is how callback functions are called and thus resulting in callback hell

analyse(() => {
    design(() => {
        develop(() => {
            test(() => {
                deploy(() => {
                    console.log("SDLC completed");
                });
            });
        });
    });
});

Enter fullscreen mode Exit fullscreen mode

Problems with callback hell:

  • Code becomes difficult to read
  • Hard to maintain
  • Error handling becomes complicated
  • Debugging becomes difficult

To solve this issue, JavaScript introduced:

Promises
Async/Await (TBD)

let's see how to reslove the callback hell with promises

CODE:

function analyse() {
    return new Promise((res, rej) => {
        setTimeout(() => {
            console.log("done analysis");
            res();
        }, 2000);
    });
}
function design(){
    return new Promise ((res,rej)=>{
        setTimeout(()=> {
            console.log("done design")
            res();
        },1000);
    })

}

function develope(){
    return new Promise ((res,rej)=>{
        setTimeout(()=> {
            console.log("done development")
            res();
        },3000);
    })

}

function test(){
    return new Promise ((res,rej)=>{
        setTimeout(()=> {
            console.log("done testing")
            res();
        },2000);
    })
}

function deploy(){
    return new Promise ((res,rej)=>{
        setTimeout(()=> {
            console.log("done deployment")
            res();
        },1000);
    })
}

function sdlc(){
    analyse().then(()=>design())
    .then(()=>develope())
    .then(()=>test())
    .then(()=>deploy())
    .then(()=>console.log("SLDC Completed"))
}

sdlc();

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Top comments (0)