Mastering Asynchronous JavaScript: Promises, Async/Await and more





Asynchronous JavaScript is a concept that enables us to execute code without interrupting the main thread, making our apps faster and more responsive. Let's dig deep into the explanation of essential asynchronous concepts in JavaScript using code examples:

1. Promises 

Promises in JavaScript describe a value that may be available immediately, in the future, or never. They are used to handle asynchronous actions and give a simpler, more legible interface for working with callbacks.

Basic Promise Example:

let promise = new Promise((resolve, reject) => {
    let isSuccess = true; // Simulate success/failure
    if (isSuccess) {
        resolve("Success!");
    } else {
        reject("Failure!");
    }
});

promise.then((message) => {
    console.log(message); // Output: Success!
}).catch((error) => {
    console.error(error);
});(code-box)

Chaining Promises:

Promise chaining is a JavaScript technique in which multiple promises are performed sequentially. Each promise in the chain is triggered by the resolution of the previous promise, allowing a series of asynchronous operations to be executed sequentially.


let promise = new Promise((resolve, reject) => {
    resolve(1);
});

promise.then((value) => {
    console.log(value); // Output: 1
    return value * 2;
}).then((value) => {
    console.log(value); // Output: 2
    return value * 3;
}).then((value) => {
    console.log(value); // Output: 6
});(code-box)

2. Async/Await

Async Await in javascript allow you to write asynchronous code that appears synchronous. An async function always returns a promise, and await i.e pauses the function's execution until the promise is resolved.

Basic Async/Await Example:


async function fetchData() {

    let promise = new Promise((resolve, reject) => {

        setTimeout(() => resolve("Data fetched!"), 2000);

    });

    let result = await promise; // Wait until the promise resolves

    console.log(result); // Output: Data fetched!

}

fetchData();(code-box)


Handling Errors with Async/Await:

We use try catch to handle error in async/awiat:

async function fetchData() {
    let promise = new Promise((resolve, reject) => {
        setTimeout(() => reject("Error fetching data!"), 2000);
    });

    try {
        let result = await promise;
        console.log(result);
    } catch (error) {
        console.error(error); // Output: Error fetching data!
    }
}

fetchData();(code-box)


3. Callbacks

Callbacks in javascript are functions that are supplied as arguments to other functions and then performed once the operation is completed.Prior to promises and async/await, this was the typical way to handle asynchronous operations..


Basic Callback Example:


 function fetchData(callback) {

    setTimeout(() => {

        callback("Data fetched!");

    }, 2000);

}


fetchData((message) => {

    console.log(message); // Output: Data fetched!

});(code-box)

Error Handling with Callbacks:

Let me explain you with how we handle errors using callbacks

function fetchData(callback) {
    setTimeout(() => {
        const error = true;
        if (error) {
            callback("Error fetching data!", null);
        } else {
            callback(null, "Data fetched!");
        }
    }, 2000);
}

fetchData((error, data) => {
    if (error) {
        console.error(error); // Output: Error fetching data!
    } else {
        console.log(data);
    }
});(code-box)

4. Event Loop

The event loop in JavaScript is a key feature that controls the execution of various pieces of code across time. It enables JavaScript to perform non-blocking operations by delegating tasks to the system whenever possible.

Event Loop Example:'

console.log("Start");

setTimeout(() => {
    console.log("Timeout"); // Executed last
}, 0);

Promise.resolve().then(() => {
    console.log("Promise"); // Executed before setTimeout
});

console.log("End");(code-box)
Output:

Start
End
Promise
Timeout(code-box)

In this example, setTimeout is pushed to the event loop, while the Promise is handled by the microtask queue, which is processed before the macrotask queue (setTimeout). 


Summary

  • Promises: Used for handling asynchronous operations with .then and .catch.
  • Async/Await: Syntactic sugar over promises, making asynchronous code look synchronous.
  • Callbacks: Functions passed as arguments to other functions, executed after an asynchronous operation completes.
  • Event Loop: Manages execution of code, events, and tasks in JavaScript.

These concepts form the core of asynchronous JavaScript and are essential for building efficient and responsive web applications.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!