What is JavaScript Async/Await, Callbacks, and Promises?

#Async/Await

#javascript

JavaScript's asynchronous programming uses Callbacks, Promises, and Async/Await, each with examples to illustrate how they work.

Callbacks

A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Example:

function fetchData(callback) {
    setTimeout(() => {
        const data = { name: "John", age: 30 };
        callback(data);
    }, 1000);
}

function displayData(data) {
    console.log(`Name: ${data.name}, Age: ${data.age}`);
}

fetchData(displayData);

In this example, `fetchData` simulates an asynchronous operation (e.g., fetching data from a server). After 1 second, it calls `callback` with the fetched data.

Promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Example:

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { name: "John", age: 30 };
            resolve(data);
        }, 1000);
    });
}

fetchData()
    .then((data) => {
        console.log(`Name: ${data.name}, Age: ${data.age}`);
    })
    .catch((error) => {
        console.error('Error:', error);
    });

In this example, `fetchData` returns a Promise. When the asynchronous operation completes successfully, `resolve` is called with the data. If there were an error, `reject` would be called. The `then` method is used to handle the resolved data, and `catch` handles any errors.

Async/Await

Async/Await is syntactic sugar built on top of Promises, providing a more synchronous-looking way to write asynchronous code.

Example:

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { name: "John", age: 30 };
            resolve(data);
        }, 1000);
    });
}

async function displayData() {
    try {
        const data = await fetchData();
        console.log(`Name: ${data.name}, Age: ${data.age}`);
    } catch (error) {
        console.error('Error:', error);
    }
}

displayData();

In this example, `fetchData` returns a Promise as before. The `displayData` function is declared as `async`, which allows the use of `await` inside it. `await` pauses the execution of `displayData` until the Promise resolves, making the code appear more synchronous and easier to read.

Summary

  1. Callbacks: Basic way to handle async code but can lead to "callback hell" with nested callbacks.
  2. Promises: A more powerful and cleaner way to handle async operations, chaining with `then` and handling errors with catch.
  3. Async/Await: Built on Promises, provides a more synchronous-looking code and better readability, especially for handling multiple asynchronous operations.

Understanding these concepts is crucial for working with asynchronous operations in JavaScript, especially in web development where you often deal with API calls, file operations, timers, and more check out Guru Labs.