Open In App

What do you mean by Asynchronous API ?

Asynchronous APIs are widely utilized in modern development because of their ability to handle multiple requests simultaneously, which improves the overall user experience. In this article, we will look into asynchronous APIs, their advantages, and how to implement them.

What are Asynchronous APIs?



Asynchronous APIs are a sort of web service that allows users to conduct multiple requests at the same time without waiting for the previous request to execute. This means that the server may process multiple requests at the same time, decreasing the API’s overall response time. Asynchronous APIs are typically utilized in scenarios involving a large number of requests or lengthy processing durations, such as data-intensive apps.

 



Advantages of Asynchronous APIs:

Implementation of Asynchronous APIs:

Below are the code implementations of Asynchronous APIs:-

Using callbacks: Fetch user data from an API using a callback function that handles success and error cases:




function getUserData(userId, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET'
`https://...com/users/${userId}`);
    xhr.onload = () => {
        if (xhr.status === 200) {
            callback(null, JSON.parse(xhr.responseText));
        } else {
            callback('Error: ' + xhr.statusText);
        }
    };
    xhr.onerror = () => {
        callback('Error: ' + xhr.statusText);
    };
    xhr.send();
}
  
getUserData(1, (error, userData) => {
    if (error) {
        console.error(error);
    } else {
        console.log(userData);
    }
});

Output:

 

Using promises: Fetch user data from an API using a Promise that resolves with the result or rejects with an error message.




function getUserData(userId) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET'
`https://...com/users/${userId}`);
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(JSON.parse(xhr.responseText));
            } else {
                reject('Error: ' + xhr.statusText);
            }
        };
        xhr.onerror = () => {
            reject('Error: ' + xhr.statusText);
        };
        xhr.send();
    });
}
  
getUserData(1)
    .then(userData => console.log(userData))
    .catch(error => console.error(error));

Output:

 

Using async/await: Fetch user data from an API using async/await syntax that waits for the response and handles errors with a try/catch block.




async function getUserData(userId) {
    const response = await fetch(`https://...com/users/${userId}`);
    if (response.ok) {
        return await response.json();
    } else {
        throw new Error('Error: ' + response.status);
    }
}
  
(async () => {
    try {
        const userData = await getUserData(1);
        console.log(userData);
    } catch (error) {
        console.error(error);
    }
})();

Output:

 

Using setTimeout(): It is a javascript function that allows executing a function after a specified amount of time




console.log('Start');
setTimeout(() => {
    console.log('Async operation');
}, 2000);
console.log('End');

Output:

 


Article Tags :