async/await

The async and await keywords simplify working with promises in JavaScript by making asynchronous code look and behave more like synchronous code.

Illustration of async_await
Illustration of async_await

💡 What is async/await?

async marks a function as asynchronous, returning a promise. await pauses the function execution until the awaited promise resolves or rejects.

Using async Functions

Declare a function with async. It implicitly returns a promise, even if you return a non-promise value.

📌 Deep Dive: async function example

JAVASCRIPT
async function greet() {
  return 'Hello!';
}

greet().then(console.log); // Logs: Hello!

Using await to Pause for Promises

await can only be used inside async functions. It waits for a promise to resolve and returns its value.

📌 Deep Dive: await example

JAVASCRIPT
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedMessage() {
  console.log('Waiting...');
  await delay(1000);
  console.log('1 second passed');
}

delayedMessage();
Output
Waiting... 1 second passed

Benefits of async/await vs. Promises

async/await vs Promise chaining
Featureasync/awaitPromise chaining
ReadabilityMore like synchronous code, easier to readNested or chained, can get complex
Error handlingUse try/catch blocksUse .catch()
Sequential operationsUse multiple await statementsChain promises
Parallel operationsUse Promise.all with awaitUse Promise.all()

Error Handling with async/await

Use try/catch inside async functions to handle rejected promises.

📌 Deep Dive: Error handling

JAVASCRIPT
async function fetchData() {
  try {
    const response = await fetch('https://does-not-exist.example');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error occurred:', error.message);
  }
}

fetchData();

⚠️ Important

Do not use await outside of async functions; it will cause a syntax error. For top-level await, modern environments support it but check compatibility.

Summary

  • async functions always return a promise.
  • await pauses async function execution until a promise settles.
  • Use try/catch to handle errors in async functions.
  • async/await improves code clarity over promise chaining.