Skip to content

Async await arrow functions

  • by

Async (await) arrow functions provide a concise and readable syntax for handling asynchronous operations in JavaScript.

In JavaScript, you can use async/await syntax with arrow functions to handle asynchronous operations. The async/await syntax provides a more readable and synchronous-looking code structure for working with promises.

The syntax for an async/await arrow function is as follows:

const functionName = async () => {
  // Code here
};
  • const declares a constant variable.
  • functionName is the name you choose for your async arrow function.
  • async is a keyword used to indicate that the function is asynchronous and will use the async/await syntax.
  • () => {} is the arrow function syntax. It represents the function’s parameters (in this case, there are none) followed by the function body enclosed in curly braces {}.

Additional examples and syntax variations for async arrow functions and async function declarations.

1. Async arrow function:

const foo = async () => {
  // do something
}

2. Async arrow function with a single argument:

const foo = async evt => {
  // do something with evt
}

3. Async arrow function with multiple arguments:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

4. Anonymous form of async arrow function:

const foo = async function() {
  // do something
}

5. Async function declaration:

async function foo() {
  // do something
}

6. Using async function in a callback:

const foo = event.onCall(async () => {
  // do something
})

7. Using async method inside of a class:

class MyClass {
  async foo() {
    // do something
  }
}

Async await arrow function example

Here’s a working example of an async/await arrow function that performs a delay and returns a resolved promise after a specified duration:

const delay = async (duration) => {
  await new Promise(resolve => setTimeout(resolve, duration));
  console.log('Delay complete!');
};

const runDelay = async () => {
  console.log('Delay started...');
  await delay(2000); // Wait for 2000 milliseconds (2 seconds)
  console.log('Continuing after delay...');
};

runDelay();

Output:

Async await arrow function

Another example

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error:', error);
  }
};

fetchData();

Here’s a real-world example of an async arrow function that retrieves weather data from an API:

const getWeatherData = async (city) => {
  try {
    const apiKey = 'YOUR_API_KEY';
    const apiUrl = `https://api.example.com/weather?city=${city}&appid=${apiKey}`;

    const response = await fetch(apiUrl);
    const data = await response.json();

    console.log(`Weather in ${city}: ${data.weather[0].description}`);
    console.log(`Temperature: ${data.main.temp}°C`);
    console.log(`Humidity: ${data.main.humidity}%`);
  } catch (error) {
    console.log('Error:', error);
  }
};

getWeatherData('London');

Do comment if you have any doubts or suggestions on this JS code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading