What is an Example of an Asynchronous Function in JavaScript ?
Last Updated :
29 Jan, 2024
An asynchronous function in programming allows multiple operations to be performed concurrently without waiting for each one to complete before moving on to the next. An example of an asynchronous function in JavaScript involves fetching data from an external source, such as an API. Let’s say we want to retrieve information from a weather API. We will make use of “fetch” to achieve this.
Example: Here, the getWeatherData
function is declared as the async
, indicating that it contains asynchronous operations. The await
keyword is used to pause the execution of the function until the asynchronous operation (in this case, fetching data from the API) is complete.
Javascript
async function getWeatherData(city) {
const apiKey = 'your_api_key' ;
const apiUrl =
`https:
try {
const response = await fetch(apiUrl);
const data = await response.json();
return data;
} catch (error) {
console.error( 'Error fetching weather data:' , error);
}
}
getWeatherData( 'NewYork' ).then((weatherData) => {
console.log( 'Weather data:' , weatherData);
});
|
Share your thoughts in the comments
Please Login to comment...