async functions in JavaScript provide a more intuitive approach to asynchronous programming. Built on Promises, they enable writing asynchronous code in a synchronous style.
Core Concepts of Async Functions
An async function is a specialized function type, essentially syntactic sugar for asynchronous operations. Introduced in the ECMAScript 2017 specification, it simplifies Promise usage and makes asynchronous code resemble synchronous code.
async function exampleFunction() {
// ...
}
Prefixing a function declaration with async declares an asynchronous function. Async functions always return a Promise. A return statement resolves the Promise with the returned value. Thrwoing an error rejects the Promise with the error object.
Implementing Async Functions
Basic Implementation
async function greet() {
return 'Hello from async';
}
greet().then(message => console.log(message)); // Output: 'Hello from async'
Here, greet returns a resolved Promise with the string 'Hello from async'.
Error Handling
async function fail() {
throw new Error('Operation failed');
}
fail().catch(err => console.error(err)); // Output: Error: Operation failed
This function returns a rejected Promise with the error object.
Combining Async and Await
Using async/await together enhances code clarity. The await keyword (usable only within async functions) pauses execution until a Promise settles.
async function fetchUser() {
const response = await fetch('https://api.github.com/users/ecma');
const userData = await response.json();
console.log(userData.login);
}
fetchUser();
Here, await suspends execution until the fetch Promise resolves before proceeding.
Practical Techniques
Error Handling with try/catch
async function safeFetch() {
try {
const response = await fetch('https://api.github.com/users/ecma');
const userData = await response.json();
console.log(userData.login);
} catch (err) {
console.error(`Fetch error: ${err}`);
}
}
safeFetch();
This uses try/catch to handle potential errors from fetch or response.json().
Handling Multiple Operations with Promise.all
async function fetchMultiple() {
try {
const [userRes, reposRes] = await Promise.all([
fetch('https://api.github.com/users/ecma'),
fetch('https://api.github.com/users/ecma/repos')
]);
const user = await userRes.json();
const repos = await reposRes.json();
console.log(user.login);
console.log(repos.length);
} catch (err) {
console.error(`Parallel fetch error: ${err}`);
}
}
fetchMultiple();
Promise.all concurrently processes multiple asynchronous operations, resuming after all complete.