Open In App

What is an Example of an Asynchronous Function in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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://api.weather.com/data/${city}?apikey=${apiKey}`;
 
  try {
      // Asynchronously fetch data
    const response = await fetch(apiUrl);
     
    // Asynchronously parse response as JSON
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching weather data:', error);
  }
}
 
// Example usage
getWeatherData('NewYork').then((weatherData) => {
  console.log('Weather data:', weatherData);
});



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads