Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await

Hello World,

Have you ever clicked a button on a website and felt like it froze for a moment? Or perhaps you’ve waited for a file to download, and your browser seemed unresponsive. This is often due to how JavaScript handles tasks that take time. Welc…


This content originally appeared on DEV Community and was authored by Sandesh S

Hello World,

Have you ever clicked a button on a website and felt like it froze for a moment? Or perhaps you've waited for a file to download, and your browser seemed unresponsive. This is often due to how JavaScript handles tasks that take time. Welcome to the world of asynchronous programming.

To make this more manageable, Javascript has evolved over time, going from callbacks to promises and finally to async/await. Each one of these solves the same problem but in increasingly better ways. Let's check how it does that.

Image description

First let's understand what are Callbacks

1. Callbacks
Callbacks are functions passed as arguments to other functions. When the first function completes its task, it 'calls back' the second function.

Let's see an example for callbacks

function fetchData(callback) {
    console.log("Fetching data...");

    // Simulating an API call with setTimeout (asynchronous)
    setTimeout(() => {
        const data = { id: 1, name: "Sandesh S"};
        console.log("Data fetched successfully.");

        // Call the callback function with the fetched data
        callback(data);
    }, 2000); // Simulating a delay of 2 seconds
}

function processData(data) {
    console.log("Processing data:", data);
}

// Calling fetchData and passing processData as a callback
fetchData(processData);

This approach solves the synchronous waiting problem, but it also has a con
Simple callbacks can lead to callback hell, where nested callbacks become difficult to read and maintain.

2. Promises
Promises offer a more structured way to handle asynchronous operations. A promise represents the eventual result of an asynchronous operation. Promises have three states: pending, fulfilled, and rejected.

Below is an example of how to create and consume a promise.

function fetchData() {
    return new Promise((resolve, reject) => {
        console.log("Fetching data...");

        setTimeout(() => {
            const success = Math.random() > 0.3; // 70% chance of success
            if (success) {
                const data = { id: 1, name: "Sandesh S"};
                console.log("Data fetched successfully.");
                resolve(data);
            } else {
                reject("Error: Failed to fetch data.");
            }
        }, 2000);
    });
}

// Using the Promise
fetchData()
    .then(data => {
        console.log("Processing data:", data);
    })
    .catch(error => {
        console.error(error);
    });

Promise chaining allows you to sequence asynchronous operations elegantly.For running multiple promises concurrently, you can use Promise.all() and Promise.race().

3. Async/Await
Async/await is syntactic sugar that makes working with promises even easier. It lets you write asynchronous code that looks like synchronous code. To use async/await, you define an async function and use the await keyword to wait for promises to resolve.

async function fetchData() {
    console.log("Fetching data...");

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const success = Math.random() > 0.3; // 70% chance of success
            if (success) {
                const data = { id: 1, name: "Sandesh S"};
                console.log("Data fetched successfully.");
                resolve(data);
            } else {
                reject("Error: Failed to fetch data.");
            }
        }, 2000);
    });
}

async function handleData() {
    try {
        const data = await fetchData();
        console.log("Processing data:", data);
    } catch (error) {
        console.error(error);
    }
}

// Calling the async function
handleData();

Comparison and Best Practices

Callbacks are the oldest approach and are suitable for simple asynchronous tasks.
Promises offer better structure and error handling. Async/await provides the cleanest and most readable syntax.
Use callbacks for simple, one-off asynchronous operations. Use promises for complex asynchronous workflows. Use async/await whenever possible for improved readability.
Always handle errors in asynchronous code. Use .catch() with promises and try...catch with async/await. Avoid deeply nested callbacks.

I hope I have tried to demystify asynchronous in javascript. Thank you!!


This content originally appeared on DEV Community and was authored by Sandesh S


Print Share Comment Cite Upload Translate Updates
APA

Sandesh S | Sciencx (2025-03-15T16:31:09+00:00) Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await. Retrieved from https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/

MLA
" » Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await." Sandesh S | Sciencx - Saturday March 15, 2025, https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/
HARVARD
Sandesh S | Sciencx Saturday March 15, 2025 » Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await., viewed ,<https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/>
VANCOUVER
Sandesh S | Sciencx - » Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/
CHICAGO
" » Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await." Sandesh S | Sciencx - Accessed . https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/
IEEE
" » Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await." Sandesh S | Sciencx [Online]. Available: https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/. [Accessed: ]
rf:citation
» Demystify asynchronous JavaScript: Callbacks, Promises, and Async/Await | Sandesh S | Sciencx | https://www.scien.cx/2025/03/15/demystify-asynchronous-javascript-callbacks-promises-and-async-await/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.