JS CodeLab
asyncintermediate

JavaScript Async Await Syntax & Live Code Examples

•
Updated

Direct Answer & Overview

The async and await keywords allow developers to write promise-based asynchronous code in a sequential, synchronous-looking style. An async function always returns a Promise, and await pauses execution until the awaited Promise settles.

#async#await#promises#es2017

JavaScript Source Code

example.js
async function main() {
  const result = await Promise.resolve("Hello async!");

  console.log(result);
}

main();

How does this JavaScript code work?

Added in ECMAScript 2017, `async/await` is syntactic sugar built on top of native Promises and generators. Marking a function with `async` ensures it always returns a Promise. Inside an async function, the `await` keyword pauses execution of that specific function until the target Promise settles, unwrapping its resolved value directly. Errors from rejected promises are handled naturally using standard `try...catch` blocks.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
Hello async!

Common mistakes to avoid

  • !Using the await keyword inside regular, non-async functions, throwing a SyntaxError.
  • !Forgetting to wrap await expressions in a try...catch block to handle possible Promise rejections.
  • !Running independent asynchronous operations sequentially with sequential awaits instead of concurrently using Promise.all().
  • !Assuming async functions execute in parallel threads; JavaScript remains single-threaded on the event loop.

Frequently Asked Questions

Can you use await at the top level of a JavaScript file?

Yes. Top-level await is fully supported in ES Modules (ECMAScript 2022+) without needing an enclosing async function wrapper.

What does an async function return if you return a primitive value?

An async function always wraps its return value in a resolved Promise. For example, returning 'hello' returns Promise.resolve('hello').

How do you handle errors with async/await?

Use standard try...catch blocks around your await expressions. If the awaited promise rejects, the error is caught by the catch block.

Comprehensive Tutorial

Want an in-depth understanding of this topic?

Read our complete, interactive tutorial covering memory management, edge cases, and best practices.

Read the full promises tutorial →