日本語

Fixing “await is only valid in async functions” in JavaScript

​​JavaScript​ES Modules,Node.js,Troubleshooting

SyntaxError: await is only valid in async functions and the top level bodies of modules appears when you use await outside a place where await is allowed. It shows up when you write await in a function that fetches JSON with fetch, or in Node.js code that reads a file, and you forgot to add async to the function. Inside a function, add async to that function. At the top level of a file, the error goes away once the file is loaded as a module.

This is a syntax error, so it appears before any function is called, at the moment the file is loaded. In my test environment, I triggered this error both in the browser console and in the Node.js terminal, and copied the messages exactly as they appeared. After the fix, I also confirmed that the error disappeared and the loaded data was displayed.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4. The browser was Chromium 153, launched headless from Playwright 1.63.0. The page was served with Python 3.11's http.server. I took console messages from the DevTools protocol and also captured screenshots of the DevTools window. I did not test Firefox or Safari, nor did I test tools such as Vite or webpack, or TypeScript.

Using await in a function without async

The page I used in the browser test had only a paragraph for showing the result, <p id="out">準備中…</p>, and <script src="main.js"></script>. (The <head> contained only the character encoding and the title.) The script was loaded as a normal script without type="module". In main.js, I wrote a function that fetches fruits.json (whose contents are ["りんご", "みかん"]) without async.

js
const out = document.getElementById('out');

function loadFruits() {
  const res = await fetch('fruits.json');
  return res.json();
}

loadFruits().then((fruits) => {
  out.textContent = fruits.join('、');
});

When I opened the page, the screen stayed at the placeholder text "Preparing…", and the DevTools Console panel showed the following.

text
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at main.js:4:15)

main.js:4:15 points to line 4, column 15 of main.js, which is the position of await.

DevTools Console panel showing Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at main.js:4:15) on a light red background
Chromium DevTools when await is used in a function without async

This error appears even if loadFruits() is never called. I changed line 1 to console.log('1行目を実行しました'); and removed the line that calls loadFruits(). The same message appeared at the same position (main.js:4:15). The console.log on line 1 did not appear in the console either. The file fails with a syntax error when it is loaded, so none of its lines run.

MDN's explanation of await says that await can only be used inside an async function or at the top level of a module. I added async before the function on line 3.

js
async function loadFruits() {
  const res = await fetch('fruits.json');
  return res.json();
}

The error no longer appeared, and the screen showed "apple, mandarin orange".

The message in the Node.js terminal

For Node.js, I prepared a main.js that reads fruits.json with readFile from node:fs/promises, instead of fetch. I did not create a package.json.

js
const { readFile } = require('node:fs/promises');

function loadFruits() {
  const text = await readFile('fruits.json', 'utf8');
  return JSON.parse(text);
}

loadFruits().then((fruits) => console.log(fruits.join('、')));

When I ran node main.js, the terminal showed the following and the exit code was 1. (I replaced the file location with /path/to/app.)

text
/path/to/app/main.js:4
  const text = await readFile('fruits.json', 'utf8');
               ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at wrapSafe (node:internal/modules/cjs/loader:1713:18)
    at Module._compile (node:internal/modules/cjs/loader:1755:20)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

Node.js v22.23.4

The output shows the line that caused the error, and ^^^^^ points to the five characters of await. Every at line below it contains node:internal/, so they are Node.js internal code. None of them are lines from my file. You can find the location from main.js:4 on the first line of the output and from the ^^^^^ marker.

As in the browser, when I changed line 3 to async function loadFruits(), the error disappeared and the terminal showed "apple, mandarin orange".

Using await inside a callback

Even if the outer function has async, you get the same error if the callback passed to forEach or a similar method does not have async. I tested this with a main.js that reads two JSON files, fruits.json and drinks.json (which contains ["お茶", "牛乳"]), in order with forEach and combines them into one array.

js
const out = document.getElementById('out');
const files = ['fruits.json', 'drinks.json'];

async function loadAll() {
  const all = [];
  files.forEach((file) => {
    const res = await fetch(file);
    all.push(...(await res.json()));
  });
  return all;
}

loadAll().then((all) => {
  out.textContent = `${all.length}件:${all.join('、')}`;
});

The error was await is only valid in async functions and the top level bodies of modules, at position main.js:7:17. The await on line 7 is inside the arrow function passed to forEach, not in loadAll. Only the outer loadAll has async, so await cannot be written there.

Adding async to the callback removes the error but gives zero results

When I added async to the callback on line 6, as in files.forEach(async (file) => {, the error stopped. However, the screen showed "0 items:". The array was still empty when loadAll returned.

MDN's description of forEach() says that forEach() takes a synchronous function and does not wait for Promises to complete. When forEach calls an async callback, it moves on without waiting for the await inside that callback.

When I replaced forEach with for...of, the await was directly inside loadAll.

js
async function loadAll() {
  const all = [];
  for (const file of files) {
    const res = await fetch(file);
    all.push(...(await res.json()));
  }
  return all;
}

The screen showed "4 items: apple, mandarin orange, tea, milk".

The callback example in MDN's error explanation shows making the callback async, building an array of Promises with map, and waiting for them with Promise.all. With this approach, the screen also showed "4 items: apple, mandarin orange, tea, milk".

js
async function loadAll() {
  const lists = await Promise.all(
    files.map(async (file) => {
      const res = await fetch(file);
      return res.json();
    }),
  );
  return lists.flat();
}

Using await outside any function (at the top level)

This case is where await is written at the top level of the file, not inside a function.

js
const out = document.getElementById('out');

const res = await fetch('fruits.json');
const fruits = await res.json();
out.textContent = fruits.join('、');

When I loaded it as a normal script (<script src="main.js">), the error await is only valid in async functions and the top level bodies of modules appeared, at position main.js:3:13.

As the message says, only modules allow await at the top level. MDN's example of top-level await in its error explanation also states that it cannot be used at the top level of a normal script, but works when the script is a module. When I changed the HTML loading to the following, without changing main.js, the error disappeared and the screen showed "apple, mandarin orange".

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

In Node.js, whether top-level await works depends on the file type

In Node.js, the result changed depending on whether the file is read as CommonJS or as an ES Module. In each case, I placed the file in a directory without a package.json and wrote const text = await readFile('fruits.json', 'utf8'); at the top level.

File How it is loaded Result
main.cjs require await is only valid in async functions and the top level bodies of modules
main.js require ERR_AMBIGUOUS_MODULE_SYNTAX error
main.js import No error. "apple, mandarin orange"
main.mjs import No error. "apple, mandarin orange"

Node.js documentation on how the module system is determined says that .cjs files are always read as CommonJS, and .mjs files are always read as ES Modules. CommonJS does not accept top-level await, so main.cjs produced the same message as inside a function. In this case, the following warning also appeared before the message. (The number after (node: is the process ID (PID). I replaced the file location with /path/to/app.)

text
(node:5614) Warning: Failed to load the ES module: /path/to/app/main.cjs. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)

To keep .cjs and fix it, move await into an async function. After rewriting it as follows, the error disappeared and the terminal showed "apple, mandarin orange".

js
const { readFile } = require('node:fs/promises');

async function main() {
  const text = await readFile('fruits.json', 'utf8');
  console.log(JSON.parse(text).join('、'));
}

main();

If the extension is .js and package.json has no type setting, Node.js decides by examining the code. The same documentation's section on syntax detection says this feature has been enabled by default since Node.js 22.7.0. Top-level await is also listed as one of the syntax features that leads Node.js to read a file as an ES Module. The main.js that used import and top-level await was read as an ES Module and ran as written.

On the other hand, a main.js that used both require and top-level await produced the following error. (I replaced the file location with /path/to/app.)

text
file:///path/to/app/main.js:1
const { readFile } = require('node:fs/promises');
                     ^

ReferenceError: Cannot determine intended module format because both require() and top-level await are present. If the code is intended to be CommonJS, wrap await in an async function. If the code is intended to be an ES module, replace require() with import.
    at file:///path/to/app/main.js:1:22
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5) {
  code: 'ERR_AMBIGUOUS_MODULE_SYNTAX'
}

Node.js v22.23.4

The message says that if you want CommonJS, you should wrap await in an async function, and if you want an ES Module, you should replace require() with import.

Modules show "Unexpected reserved word" instead

The same mistake produced a different message in a file loaded as a module. When I loaded the first main.js, the one with loadFruits that lacked async, using <script type="module" src="main.js">, the Console panel showed the following.

text
Uncaught SyntaxError: Unexpected reserved word (at main.js:4:15)
DevTools Console panel showing Uncaught SyntaxError: Unexpected reserved word (at main.js:4:15) on a light red background
Chromium DevTools when loaded as a module and await is used in a function without async

In Node.js, I changed the require in the main.js from the previous section to import, saved it as main.mjs, and ran node main.mjs. It showed SyntaxError: Unexpected reserved word. As with CommonJS, ^^^^^ points to await.

MDN's explanation of the reserved word error says that Unexpected reserved word appears in environments that use V8, such as Chromium, when a reserved word is used as an identifier (such as a variable name). The message does not mention await or async, but if the position points at await, the fix is the same as in the first case: add async to the function. In my test environment, adding async before function removed the error in the browser and the screen showed "apple, mandarin orange". In main.mjs, the terminal also showed "apple, mandarin orange".

Point

Check whether the innermost function that contains the await has async. If the await is inside a callback, the callback itself needs async.

MDN's explanation of this error says the wording of this error differs by browser: Firefox shows await is only valid in async functions, async generators and modules, and Safari shows Unexpected identifier.

​Posted by 86