'await' expression is only allowed within an async function

avatar

Borislav Hadzhiev

Last updated: Mar 12, 2022

banner

Photo from Unsplash

'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; }

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

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; }

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); }); }

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.

Conclusion #

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.

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.