task 3

PHOTO EMBED

Wed Apr 23 2025 01:40:45 GMT+0000 (Coordinated Universal Time)

Saved by @cciot

1. Working with Higher-Order Functions in JavaScript
A higher-order function is a function that either takes another function as an argument or returns a function.

// Higher-order function
function greetUser(greetFn) {
    const name = "Alice";
    greetFn(name);
}
// Function to be passed
function sayHello(name) {
    console.log(`Hello, ${name}!`);
}
greetUser(sayHello);

2. Callback and Callback Hell
A callback is a function passed to another function to be executed later.

Example with Callback Hell:
function step1(callback) {
    setTimeout(() => {
        console.log("Step 1 completed");
        callback();
    }, 1000);
}

function step2(callback) {
    setTimeout(() => {
        console.log("Step 2 completed");
        callback();
    }, 1000);
}

function step3(callback) {
    setTimeout(() => {
        console.log("Step 3 completed");
        callback();
    }, 1000);
}

// Callback Hell
step1(() => {
    step2(() => {
        step3(() => {
            console.log("All steps completed (callback hell)");
        });
    });
});

3. Working with XHR (XMLHttpRequest)

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("XHR Response:", JSON.parse(xhr.responseText));
    }
};
xhr.send();

4. Using Promises to Deal with Callback Hell
Promises provide a cleaner alternative to callbacks for handling async tasks.

function stepPromise(stepName) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(`${stepName} completed`);
            resolve();
        }, 1000);
    });
}
// Promise chaining to avoid callback hell
stepPromise("Step 1")
    .then(() => stepPromise("Step 2"))
    .then(() => stepPromise("Step 3"))
    .then(() => console.log("All steps completed (with Promise)"));

5. Promise Chaining and async/await

Promise Chaining (already shown above)

Using async/await (cleanest syntax)

async function executeSteps() {
    await stepPromise("Step 1");
    await stepPromise("Step 2");
    await stepPromise("Step 3");
    console.log("All steps completed (with async/await)");
}

executeSteps();
content_copyCOPY