Async/Await in JavaScript: A Comprehensive Guide for Developers

JavaScript
3 minutes read

Introduction

Hello developers! Today, we’ll be diving deep into one of the most powerful and essential concepts in JavaScript – async/await. Whether you’re a new or an experienced developer, understanding async/await is a skill you’ll definitely want in your toolkit. So, let’s get started!

What is Async/Await?

Async/Await is a syntactic sugar in JavaScript that allows us to write asynchronous code in a more synchronous or linear manner. It’s built on top of Promises and makes the code easier to read and understand. In essence, async/await helps us deal with the ‘callback hell’ problem that often arises with asynchronous JavaScript.

async function exampleFunction() {
  const data = await fetchData(); // Fetch data asynchronously
  console.log(data);
}

In the above example, the fetchData function is assumed to return a Promise. The await keyword is used to pause the execution of exampleFunction until the Promise is resolved or rejected.

The Await Operator

The await operator is used to pause the execution of an async function and waits for a Promise‘s resolution or rejection. The function execution resumes once the Promise is settled, and the resolved value is returned. If the Promise is rejected, await throws the rejection value. Keep in mind that await can only be used inside an async function.

async function getTodos() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos');
  const data = await response.json();
  console.log(data);
}
getTodos();

In this example, fetch returns a Promise that resolves the response to that request, whether it is successful or not.

Async Functions

An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them. Although the return value of an async function behaves as if it’s wrapped in a Promise.resolve, they are not equivalent. If an await expression is present in the function body, the async function will always complete asynchronously.

async function helloWorld() {
  return 'Hello, world!';
}

helloWorld().then((value) => console.log(value)); // 'Hello, world!'

In the above example, the async function helloWorld returns a Promise that resolves to ‘Hello, world!’.

Examples of Using Async/Await

Let’s explore an example that outlines the use of async/await in JavaScript:

// Define a function that returns a Promise that resolves after a set time
function resolveAfterSeconds(seconds) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(`Resolved after ${seconds} seconds`);
    }, seconds * 1000);
  });
}

// Define an async function
async function asyncCall() {
  console.log('Calling the function...');

  // Use await to wait for the Promise to resolve
  const result = await resolveAfterSeconds(3);

  // Log the result of the Promise
  console.log(result);
}

// Call the async function
asyncCall();

In this example, resolveAfterSeconds is a function that returns a promise that resolves after a specified number of seconds. The asyncCall function is declared with the async keyword, which means it will return a promise. Inside this function, the await keyword is used to pause the execution of the function until the promise returned by resolveAfterSeconds is resolved. The result of the promise is then logged into the console.

When you run this code, it will log “Calling the function…” immediately, and then “Resolved after 3 seconds” after a delay of 3 seconds.

Error Handling in Async/Await

In an async function, errors can be handled using try/catch blocks. If a Promise is rejected in an await expression, the error will be thrown and can be caught and handled.

async function handleError() {
  try {
    const response = await fetch('https://invalidurlurl'); // This will fail
    const data = await response.json();
    console.log(data);
} catch (error) {
    console.error('An error occurred: ', error);
    }
}

handleError();

In this example, we try to fetch from an invalid URL. This will fail, and the error will be caught and logged into the console.

Further Reading

Conclusion

In conclusion, the async/await syntax in JavaScript offers a more readable and concise approach to working with asynchronous operations, compared to traditional promise-based or callback-based code. 

With async/await, we can write code that’s much easier to read and reason about. However, it’s important to note that async/await is just syntactic sugar on top of promises, and understanding promises is crucial to properly grasp async/await. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *