Open In App

What do you mean by Asynchronous API ?

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Improved Performance: multiple requests can be handled, thereby improving the overall performance of the application.
  • Scalability: Asynchronous APIs are extremely scalable, which implies that as the application expands, they can manage a rising number of requests. This is due to the server’s ability to handle requests in parallel, reducing total response time.
  • Resource Efficiency: Asynchronous APIs require fewer resources to handle multiple requests compared to synchronous APIs. This means that developers can build more efficient and cost-effective applications.

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:

Javascript




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.

Javascript




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.

Javascript




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

Javascript




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


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads