Reputation: 569
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
Upvotes: 1
Views: 78
Reputation: 13693
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);
})()
Upvotes: 1
Reputation: 18240
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(...)
Upvotes: 3