Last updated: Feb 28, 2024
Reading time·2 min
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.
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 aren't able to use the
await
keyword in it.
async
To solve the error, mark the directly enclosing function as async
.
// 👇️ mark as async async function getNum() { const num = await Promise.resolve(42); return num; }
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.
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
.
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.
I've written a detailed guide on how to type an async function.
You can learn more about the related topics by checking out the following tutorials: