'await' expression is only allowed within an async function

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
2 min

banner

# 'await' expression is only allowed within an async function

The error "await expression is only allowed within an async function" occurs when the await keyword is used inside of a function that was not marked as async.

To solve the error and use the await keyword, mark the directly enclosing function as async.

Here is an example of how the error occurs.

index.ts
function getNum() { // ⛔️ Error: 'await' expressions are only allowed within async functions and at the top levels of modules.ts(1308) const num = await Promise.resolve(42); return num; }

await expressions are only allowed within async function

We didn't declare the getNum function as async, so we aren't able to use the await keyword in it.

# Mark the directly enclosing function as async

To solve the error, mark the directly enclosing function as async.

index.ts
// 👇️ mark as async async function getNum() { const num = await Promise.resolve(42); return num; }

mark directly enclosing function as async

The code for this article is available on GitHub

# Forgetting to mark callback functions as async

A very common cause of the error is forgetting to set an inner function as async, e.g. the ones we pass to methods like forEach, map, etc.

index.ts
async function loopNumbers() { [1, 2, 3].forEach((num) => { // ⛔️ Error: 'await' expressions are only allowed within async functions and at the top levels of modules.ts(1308) await Promise.resolve(num); }); }

We marked the loopNumbers function as async, but we're using the await keyword inside of the function we passed to the forEach() method.

Instead, we should have marked the function we passed to forEach as async.

index.ts
function loopNumbers() { // 👇️ inner function is async, // because it uses await [1, 2, 3].forEach(async (num) => { await Promise.resolve(num); }); }

mark correct function as async

The code for this article is available on GitHub

We declared the function we passed to the forEach() method as async, and now we can use the await keyword in it.

The directly enclosing function has to be marked async for us to be able to use the await keyword.

I've written a detailed guide on how to type an async function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.