0

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);
1
  • 4
    As it says, await can only be used in an async function. Whatever the surrounding function is, mark it as async. Commented Jun 8, 2022 at 13:49

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.