Callbacks vs Promises vs Async/Await Concept in JavaScript

ayas_tech_2b0560ee159e661

Ayas Hussein

Posted on June 6, 2024

Callbacks vs Promises vs Async/Await Concept in JavaScript

JavaScript (JS) provides several ways to handle asynchronous operations, which are crucial for tasks like fetching data from an API, reading files, or performing time-consuming computations without blocking the main thread. Let's explore the three main approaches: Callbacks, Promises, and Async/Await.

What is a Callback ?
A callback is a function passed into another function as an argument and is executed after some operation has been completed. Callbacks are one of the oldest ways to handle asynchronous operations in JavaScript

function fetchData(callback) {
    setTimeout(() => {
        const data = { user: 'John Doe' };
        callback(null, data);
    }, 1000);
}

fetchData((error, data) => {
    if (error) {
        console.error(error);
    } else {
        console.log(data);
    }
});

Enter fullscreen mode Exit fullscreen mode

In this example, fetchData takes a callback function as an argument. After a delay of 1 second, the callback function is executed with the data.

What is a Promise ?
Definition: A promise is an object representing the eventual completion or failure of an asynchronous operation.It provides a cleaner way to handle asynchronous code, avoiding nested callbacks.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { user: 'John Doe' };
            resolve(data);
        }, 1000);
    });
}

fetchData()
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

Enter fullscreen mode Exit fullscreen mode

What are Async/Await ?
Async and await are syntactic sugar built on top of promises. They provide a more straightforward way to work with asynchronous code, making it easier to read and write.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { user: 'John Doe' };
            resolve(data);
        }, 1000);
    });
}

async function fetchUser() {
    try {
        const data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

fetchUser();

Enter fullscreen mode Exit fullscreen mode

Conclusion
Choosing between callbacks, promises, and async/await depends on your specific use case and the complexity of your asynchronous code. For simple tasks, callbacks may suffice. For more complex scenarios involving multiple asynchronous operations, promises or async/await offer better readability and maintainability.

💖 💪 🙅 🚩
ayas_tech_2b0560ee159e661
Ayas Hussein

Posted on June 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related