I don't know what is wrong with this code. It throws an error in the console that says :
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
Can anyone tell me what's wrong with my usage of await?
let user = {
name: 'George',
surname: 'Arqael'
};
let regUser = await fetch(url, {
method: 'post',
headers: {
'Content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(user)
});
let result = await regUser.json();
console.log(result);
Await requires async. You should be able to wrap it in an async function.
async function f() {
let regUser = await fetch(url, {
method: 'post',
headers: {
'Content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(user)
});
let result = await regUser.json();
console.log(result);
}
As the error says, top-level await is only available in modules. If you add type="module" to your script tag it will work as expected.
<script type="module">
let user = {
name: 'George',
surname: 'Arqael'
};
let regUser = await fetch(url, {
method: 'post',
headers: {
'Content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(user)
});
let result = await regUser.json();
console.log(result);
</script>
Or, wrap your code in an async function as MortBort suggested.