To return the response from an asynchronous call in JavaScript, it’s important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it uses asynchronous programming to execute tasks without blocking the main thread.

You can manage asynchronous calls using callbackspromises, or the async/await syntax, as well as the Promise syntax. These methods help return responses efficiently and improve the readability and maintainability of the code.

Return Response using a Callback Function

function fetchData(callback) {
    setTimeout(() => {
        const s = "Return Response Using a Callback Function";
        callback(s);
    }, 1000);
}

// Using the callback
fetchData((response) => {
    console.log(response); 
});

Return Response using Promises

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const s = "Return Response Using Promises";
            resolve(s);
        }, 1000);
    });
}

// Using the promise
fetchData()
    .then((response) => {
        console.log(response); 
    })
    .catch((error) => {
        console.error("Error:", error);
    });

Return Response using Async/Await

async function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const a = "Return Response Using Async/Await";
            resolve(a);
        }, 1000);
    });
}

async function getData() {
    try {
    
        // Waits for the promise to resolve
        const response = await fetchData();
        console.log(response);
    } catch (error) {
        console.error("Error:", error);
    }
}

getData();

Similar Posts