NashTech Blog

Understanding JavaScript Promises and Callbacks

Table of Contents
promise and callback

JavaScript is an asynchronous programming language, meaning it is able to perform a couple of tasks concurrently without blocking the primary thread. Two key capabilities that facilitate this are callbacks and promises. Understanding these concepts is critical for coping with asynchronous operations successfully. In this blog, we will be exploring about JavaScript promises creation, usage and chaining. We will also be learning about callback, its issues and example.

Callbacks

A callback is a function passed into another function as an argument, that’s then invoked within the outer function to complete some kind of routine or action. Callbacks had been a staple in JavaScript for dealing with asynchronous operations, inclusive of reading files, making HTTP requests, or performing different tasks that take time to finish.

Example of a Callback

Let’s see an easy example of a callback function.

function greet(name, callback) {
    console.log('Hello ' + name);
    callback();
}

function sayGoodbye() {
    console.log('Goodbye!');
}

greet('Alice', sayGoodbye);

In this example, the sayGoodbye function is passed as a callback to the greet function. After greeting Alice, it calls sayGoodbye.

Issues with Callbacks

While callbacks are effective, they could cause what is usually known as “callback hell” or “pyramid of doom.” This takes place when multiple asynchronous operations are chained together, resulting in deeply nested code that is hard to read, understand and maintain.

doSomething(function(result) {
    doSomethingElse(result, function(newResult) {
        doAnotherThing(newResult, function(finalResult) {
            console.log(finalResult);
        });
    });
});

Promises

Promises are a modern alternative to callbacks, imparting a cleaner and greater sturdy manner to address asynchronous operations. A promise represents a value that may be available now, or in the future, or never.

A promise can be in one of three states:

Pending: It is the initial state of a promise, in this state its neither fulfilled or nor rejected.

Fulfilled: In this state the operation has completed successfully.

Rejected: This state depicts that the operation has failed.

Creating a Promise

You can create a promise with the use of the Promise constructor, which takes a function with two arguments: resolve and reject.

let myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Success!');
    }, 2000);
});

Using a Promise

To handle the result of a promise, you use the then method for a success results and catch for errors.

myPromise.then((message) => {
    console.log(message);
}).catch((error) => {
    console.log(error);
});

Chaining Promises

One of the most important benefits of promises is their capacity to chain operations, making the code more readable and maintainable.

doSomething()
    .then(result => doSomethingElse(result))
    .then(newResult => doAnotherThing(newResult))
    .then(finalResult => {
        console.log(finalResult);
    })
    .catch(error => {
        console.log(error);
    });

Example: Fetching Data with Promises

Let’s have a look at an instance of the use of promises with the Fetch API to get data from a server.

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

Conclusion

Both callbacks and promises are vital for dealing with asynchronous operations in JavaScript. While callbacks are simpler and were used for a long term, promises offers a more effective and flexible manner to manipulate asynchronous code, warding off the troubles of callback hell and offering a more readable and maintainable approach. As you still work with JavaScript, studying these principles will significantly enhance your ability to write efficient and effective asynchronous code.

For more such blogs and updates follow Front-end Competency.

Follow NashTech Blogs for more amazing blogs.

Happy Coding!

Picture of Saurabh

Saurabh

Saurabh is a Software Consultant at Nashtech. He is passionate about Front-end Development and like taking up challenges. He majorly work on front-end tech like React.js and Next.js. As a hobby he like reading Tech articles, riding and travelling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top