'Why does this function call throws "await is only valid in async function" Syntax Error even though the function is async?

There is a loadJson function that returns the Json of a firebase link

async function loadJson(url) {
    let response = await fetch(url)
    let data = await response.json()
    return data
}

I am trying to assign the value of loadJson() to this variable and use it in a promise.

let indexJSON = await loadJson(url)

indexJSON.then(() => {      
    // some code
})

But why does this code throws the following error?

Uncaught SyntaxError: await is only valid in async function


Solution 1:[1]

You could go with a IIFE and make use of async-await, otherwise use then to evaluate the promise.

(async () => {
  let indexJSON = await loadJson(url)
  console.log(indexJSON);
})()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1