How can I handle asynchronous operations such as fetching data from an API by using JavaScript?

263    Asked by DanielBAKER in Salesforce , Asked on Feb 9, 2024

 I am particularly developing a web-based project. In this particular task, how can I handle asynchronous operations like as fetching data from an API by using the JavaScript promises considering proper error handling and managing the pending state during the time of waiting for data for the task of resolving or rejecting? 

 In the context of Salesforce, you can do so by using the following steps:-

Async operations with promise

You can use a promise for handling asynchronous operations such as API calls.

Function fetchDataFromAPI() {
    Return new Promise((resolve, reject) => {
        // Simulate an asynchronous API call
        setTimeout(() => {
            const success = Math.random() > 0.5; // Simulate success or failure
            if (success) {
                resolve(“Data successfully fetched”);
            } else {
                Reject(“Error fetching data”);
            }
        }, 2000); // Simulate a 2-second delay
    });
}
Handling pending state
You can use the pending state during the time of waiting for the promise to be resolved or rejected.
Const dataPromise = fetchDataFromAPI();
// Example of handling pending state
Console.log(“Fetching data…”);
dataPromise
    .then((data) => {
        Console.log(“Data resolved:”, data);
        // Handle successful data retrieval
    })
    .catch((error) => {
        Console.error(“Data rejected:”, error);
        // Handle error case
    });
Async Function with promise
You can use the async/await for the task of cleaning asynchronous code.
Async function fetchData() {
    Try {
        Const data = await fetchDataFromAPI();
        Console.log(“Data resolved:”, data);
        // Handle successful data retrieval
    } catch (error) {
        Console.error(“Data rejected:”, error);
        // Handle error case
    }
}
fetchData();


Your Answer

Interviews

Parent Categories