-1

I am trying to obtain the result of this 'response' into a variable that I can manipulate later. This is what I have so far

const url = my-url
const axios = require('axios').default;

async function getUser() {
    try {
      const response = await axios.get(url);
      //console.log(response); // this is what I need
      return response.data
    } catch (error) {
      console.error(error);
    }
  }


let results = await getUser();
console.log(results) // take results and do something with it

I do not understand why I cannot access the results.

redditor
  • 4,196
  • 1
  • 19
  • 40
  • @Phil I have edited my question, that may have been a typo – redditor Aug 10 '22 at 23:57
  • There doesn't appear to be anything specifically wrong with your code. What happens? Do you have any errors reported? – Phil Aug 10 '22 at 23:58
  • @Phil, sorry I should have included that `await is only valid in async functions and the top level bodies of modules` – redditor Aug 10 '22 at 23:59
  • @Phil I wasn't sure if there was a better way overall, thanks. – redditor Aug 10 '22 at 23:59
  • 1
    To fix that, put the code `let results = await getUser();` and `console.log(results)` inside an `async` function and call that function. (alternatively, run your code in an environment that supports top-level await, though that solution may not be practical) – Nicholas Tower Aug 11 '22 at 00:01
  • 1
    This appears to be the _"top level body of a module"_. If it's not then there's something missing from your question – Phil Aug 11 '22 at 00:02

1 Answers1

-1

This is called a top-level await and not all runtimes support it

...I assumed you are not inside a function because i saw the require statement const axios = require('axios').default; on the top

Kadir Damene
  • 358
  • 1
  • 3
  • 10