为什么即使函数是异步的,这个函数调用也会抛出 "await is only valid in async function" 语法错误?

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

有一个 loadJson 函数 returns firebase Json link

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

我正在尝试将 loadJson() 的值分配给此变量并在承诺中使用它。

let indexJSON = await loadJson(url)

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

但是为什么这段代码会抛出以下错误?

Uncaught SyntaxError: await is only valid in async function

你的问题是你的 await 这里:

let indexJSON = await loadJson(url)

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

如果你想在没有 await 的情况下调用函数:

let indexJSON = loadJson(url)
indexJSON.then(...)

您可以使用 IIFE 并使用 async-await,否则使用 then 来评估承诺。

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