Solve - await is only valid in Async Functions Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Luigi Manga

Solve - await is only valid in Async Functions Error #

The "await is only valid in async functions" error occurs when the await keyword is used inside of a function that was not marked as async. To use the await keyword inside of a function, mark the directly enclosing function as async.

await is only valid in async functions

Here is an example of how the error occurs.

index.js
function sum() { // โ›”๏ธ await is only valid in async functions and top // โ›”๏ธ level bodies of modules const num = await Promise.resolve(100); return num; }

Because we didn't declare the sum function as async we are not able to use the await keyword in it. Instead we should set the function as async.

index.js
async function sum() { // โœ… works const num = await Promise.resolve(100); 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.

Keep in mind that the directly enclosing function has to be marked as async for you to be able to use the await keyword.

index.js
async function example() { [1, 2, 3].forEach(num => { // โ›”๏ธ await is only valid in async functions and top // โ›”๏ธ level bodies of modules await Promise.resolve(num); }); }

We marked the example function as async, however we're using the await keyword inside of the function we passed to the forEach method.

We should have instead made the function we passed to forEach async. Here's how to solve this.

index.js
function example() { [1, 2, 3].forEach(async num => { await Promise.resolve(num); }); }

We declared the function we passed to the forEach method as async, therefore we are able to 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.

If you're trying to use the await keyword on the top level, make sure you set the type attribute to module in your package.json file if you're using node.js or set the attribute in a script tag on the browser.

Here's how to use top level await in Node.js:

Create package.json file if you don't have one already:

shell
npm init -y

Add the type property and set it to module in your package.json file.

package.json
{ "type": "module", "name": "javascript", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

Now you can use top level await in your Node.js application, e.g.

index.js
console.log(await Promise.resolve(10));

If you're on the browser, set the type attribute to module in your script tag.

index.html
<script type="module" src="index.js"></script>

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee