Starting with ES13/ES2022, in top-level modules, you can use await
without having to wrap it in an async
function, for example, like so:
// ES13+
// main.js
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data); // { ... }
<script type="module" src="main.js"></script>
However, you can't use await
without async
in non-top-level modules. In such cases, you must always wrap it in an async
function, for example, like so:
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data); // { ... }
}
fetchData();
If you attempt to use await
outside an async
function in non-top-level modules, it will result in a syntax error:
// SyntaxError: await is only valid in async functions and the top level bodies of modules
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
// ...
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.