Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
Trying to use await in Javascript but it's returning error

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);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!