Back to JavaScript
2026-01-095 min read

await using (JavaScript)

Learn await using (JavaScript) step by step with clear examples and exercises.

Title: Mastering await in JavaScript: A full guide

Why This Matters

In this lesson, we'll delve into the powerful await keyword in JavaScript, a big help for handling asynchronous operations with ease. By understanding how to use await, you'll be better prepared for real-world coding scenarios, interviews, and debugging common asynchronous issues.

Prerequisites

To follow this lesson effectively, you should have a good grasp of the following concepts:

  • JavaScript syntax and variables
  • Callbacks and Promises
  • ES6 features like arrow functions, template literals, and destructuring assignments
  • Understanding of error handling using try...catch blocks

Deep Dive into Prerequisites

  1. JavaScript Syntax and Variables: Familiarize yourself with basic JavaScript syntax, data types, variables, and control structures.
  1. Callbacks: Learn how to handle asynchronous operations using callback functions, which are passed as arguments to other functions and executed after the asynchronous operation is complete.
  1. Promises: Understand Promises, which provide a more elegant way of handling asynchronous operations by returning an object that represents the eventual completion or failure of an asynchronous operation.
  1. ES6 Features: Familiarize yourself with ES6 features like arrow functions, template literals, and destructuring assignments to make your JavaScript code cleaner and more efficient.
  1. Error Handling using try...catch blocks: Learn how to handle errors in JavaScript using the try...catch block, which allows you to catch exceptions and handle them appropriately.

Core Concept

Understanding await

In JavaScript, asynchronous operations are typically handled using callbacks or Promises. However, these methods can make your code harder to read and manage, especially when dealing with multiple asynchronous tasks. This is where await comes in, simplifying the process by allowing you to write asynchronous code that looks and behaves like synchronous code.

The await keyword is used within an async function (which we'll discuss next) to pause the execution of the function until a Promise is resolved or rejected. When await is applied to a Promise, it automatically unwraps the Promise and returns its result or throws the error if one occurs.

Writing an async Function

To create an async function, simply prefix the function declaration with the keyword async. Inside this function, you can use the await keyword before any Promise to pause the execution until that Promise is resolved or rejected. Here's a simple example:

async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}

fetchData();

In this example, fetchData is an async function that fetches data from a hypothetical API and logs it to the console. The await keyword is used twice: first with the fetch() function to wait for the response, and again with response.json() to wait for the JSON data.

Handling Errors with try...catch

When using await, you should be aware that any errors that occur within the Promise will be passed up the call stack and caught by a try...catch block surrounding the async function. Here's an example:

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

fetchData();

In this example, the try...catch block catches any errors that may occur during the execution of the async function and logs them to the console.

Caveats and Limitations

Note that that you can only use await within an async function. Additionally, the function must return a Promise if you want to use the results outside of the function.

async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}

fetchData().then(data => console.log(data));

In this example, the async function returns a Promise containing the fetched data, which is then logged to the console using the then() method.

Worked Example

Let's work through an example that demonstrates how to use await to fetch and process data from multiple APIs asynchronously:

async function getData() {
try {
const api1Response = await fetch('https://api.example1.com/data');
const api1Data = await api1Response.json();

const api2Response = await fetch('https://api.example2.com/data');
const api2Data = await api2Response.json();

// Process the data here...
console.log(api1Data, api2Data);
} catch (error) {
console.error(`Error: ${error}`);
}
}

getData();

In this example, the async function fetches data from two different APIs and processes them after they have been resolved. If an error occurs during any of the API calls, it will be caught by the try...catch block and logged to the console.

Common Mistakes

  1. Forgetting the async keyword: An async function is required for using await. Make sure you prefix your function with the async keyword.
  1. Using await outside an async function: You can only use await within an async function. If you encounter errors, double-check that your function is declared as async.
  1. Not handling errors: When using await, make sure to handle any potential errors by wrapping the async function in a try...catch block.

Common Mistakes (Continued)

  1. Misusing await with non-Promise values: The await keyword can only be used with Promises, not with regular values or objects. If you try to use it with a non-Promise value, JavaScript will throw an error.
  1. Not returning a Promise from an async function: If you want to use the result of an async function outside of the function itself, make sure it returns a Promise.

Practice Questions

  1. Write an async function that fetches data from three different APIs and logs their response statuses (200 OK, 404 Not Found, etc.).
  1. Given the following async function, find and fix the mistake:
async function fetchData() {
const apiResponse = await fetch('https://api.example.com/data');
const data = await apiResponse.json();
console.log(data);
}

fetchData();

FAQ

  1. Can I use await with Promises that don't return data?

Yes, you can use await with any Promise, even those that don't return data. However, the result of such a Promise will be undefined.

  1. What happens if an async function returns multiple values?

When an async function returns multiple values, it implicitly returns a Promise that resolves to an array containing all returned values.

  1. Can I use await with arrow functions?

Yes, you can use await within arrow functions as long as the enclosing function is declared as async. However, keep in mind that arrow functions do not have their own this value, so be aware of any potential issues this may cause.

  1. How does await affect the flow of control in an async function?

When you use await inside an async function, the execution of the function pauses until the Promise is resolved or rejected. Once the Promise resolves or rejects, the execution continues from where it left off. This allows you to write asynchronous code that behaves like synchronous code.

await using (JavaScript) | JavaScript | XQA Learn