Open In App

How to convert an onload promise into Async/Await ?

In this article, we will learn how to unload promise into Async/Await with multiple approaches.

An onload promise is a promise that is resolved when any onload event is fired onto a DOM ( Document Object Model ) element. The onload event is fired when the element has finished loading all of its resources, such as images and scripts. It’s like a commitment that happens when the element is all set and ready to go.



Promises are a way to handle asynchronous operations, representing a value that might not be available yet. It provides readable and manageable code by handling callbacks in a well-structured manner.

Async/Await is a modern method that simplifies working with promises. It provides a cleaner syntax by using async functions to deal with asynchronous methods, making code easier to understand and maintain. It also allows the use of await to handle promises in a more linear and synchronous style, enhancing code readability.



Example: In this example, we will see how we can fetch data by using onload promise.




// Original code using onload promise
  
function fetchUserData(url) {
    return new Promise((resolve, reject) => {
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    reject
                        (new Error('Failed in fetching the user data: ' 
                                    + url));
                }
                return response.json();
            })
            .then(userData => console.log(userData))
            .catch(error => reject(error));
    });
}
  
fetchUserData("https://...example.com/");

Output:

Output

Example 2: In this example, we will see how we can convert onload promise into Async/Await.




// Convert to async/await
  
async function fetchUserDataAsync(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error
                ('Failed in fetching the user data: ' + url);
        }
        const userData = await response.json();
        return userData;
    } catch (error) {
        throw new Error(error);
    }
}
  
  
async function getUserInfo() {
    try {
        const userData = await
            fetchUserDataAsync('https://...example.com/');
        userData.forEach(item => {
            console.log(`ID: ${item.id}, 
            Title: ${item.title}`);
        });
    } catch (error) {
        console.error('Error:', error.message);
    }
}
  
getUserInfo();

Explanation:

Output:

 


Article Tags :