Skip to content
Advertisement

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

Advertisement

Answer

your problem is your await here:

let indexJSON = await loadJson(url)

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

if you want the promise call the function without await:

let indexJSON = loadJson(url)
indexJSON.then(...)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement