What does the async keyword do?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #Asynchronicity #JS Basics

Brief Answer

The async keyword before a function makes it asynchronous. Such a function always returns a Promise, even if it returns a regular value. The async keyword allows using the [await] keyword inside the function to wait for other asynchronous operations.

// Regular function
function normalFunc() {
  return 'result';
}
 
// Asynchronous function
async function asyncFunc() {
  return 'result';
}
 
// Difference in return value
console.log(normalFunc());    // 'result'
console.log(asyncFunc());     // Promise { 'result' }
 
// Usage with await
async function getData() {
  const result = await asyncFunc();
  console.log(result); // 'result'
}

Full Answer

The [async] keyword is like a special label on a function that says: “This function works with asynchronous operations”. It’s like a notification on a mailbox — it tells the postman that there might be special letters inside requiring special delivery! 📬

What async Does

The [async] keyword before a function:

  1. Automatically returns a Promise — even if the function returns a regular value
  2. Allows using await — inside such a function you can wait for asynchronous operations
  3. Makes code cleaner — eliminates [.then()] chains

Simple Examples

Basic async Usage

// Asynchronous function with regular return
async function greet() {
  return 'Hello!';
}
 
// Same as:
// function greet() {
//   return Promise.resolve('Hello!');
// }
 
greet().then(message => console.log(message)); // 'Hello!'

Async with await

// Function simulating asynchronous operation
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
// Asynchronous function with await
async function delayedGreeting() {
  console.log('Starting...');
  await delay(1000); // Wait 1 second
  return 'Done!';
}
 
// Usage
delayedGreeting().then(result => console.log(result));

How async Works

Automatic Conversion to Promise

async function withValue() {
  return 'value';
}
 
async function withPromise() {
  return Promise.resolve('value');
}
 
// Both functions return Promise
console.log(withValue());  // Promise { 'value' }
console.log(withPromise()); // Promise { 'value' }

Error Handling

async function mightFail() {
  throw new Error('Error!');
}
 
// Same as:
// function mightFail() {
//   return Promise.reject(new Error('Error!'));
// }
 
mightFail().catch(error => console.log(error.message)); // 'Error!'

When to Use async

For Working with Asynchronous Operations

// Working with network
async function fetchUserData(userId) {
  // Simulating server request
  const response = await fetch('/api/users/' + userId);
  const userData = await response.json();
  return userData;
}

For Simplifying Code

// Instead of .then() chains
// fetch('/api/data')
//   .then(response => response.json())
//   .then(data => processData(data))
//   .then(result => console.log(result))
//   .catch(error => console.log(error));
 
// Better to use async/await
async function handleData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    const result = processData(data);
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

Common Mistakes

Forgetting async Before await

// ❌ Error — await outside async function
// function bad() {
//   const result = await somePromise(); // SyntaxError!
// }
 
// ✅ Correctly
async function good() {
  const result = await somePromise(); // Works!
}

Not Handling Errors

// ❌ Error — error not handled
// async function risky() {
//   const data = await fetch('/api/data');
//   // If fetch fails, error will "fall" up
// }
 
// ✅ Correctly — error handling
async function safe() {
  try {
    const data = await fetch('/api/data');
  } catch (error) {
    console.log('Error:', error);
  }
}

Simple Rules

  1. async — makes function asynchronous and always returns Promise 📦
  2. await — can be used only inside async functions ⏱️
  3. Readability — async/await makes asynchronous code look like synchronous 📖
  4. Errors — use try/catch for error handling in async functions ⚠️
  5. Chains — eliminates long [.then()] chains 🔗

The [async] keyword is a simple way to work with asynchronous code, making it more readable and understandable. This is a modern standard for writing asynchronous JavaScript! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪