【问题标题】:Why does this function call throws "await is only valid in async function" Syntax Error even though the function is async?为什么即使函数是异步的,此函数调用也会抛出“await 仅在异步函数中有效”语法错误?
【发布时间】:2020-08-15 10:39:11
【问题描述】:

有一个loadJson函数可以返回firebase链接的Json

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

【问题讨论】:

  • javascript.info/async-await | “等待在顶级代码中不起作用”。您的 loadJson() 返回异步函数,因此您不必等待它,何时准备好将返回您的数据值。尝试做 loadJson(url).then(()=>{}) 或 let indexJSON = loadJson(url),将必须工作。 Await 只能存在于异步函数中。

标签: javascript ecmascript-2016


【解决方案1】:

你的问题是你的await这里:

let indexJSON = await loadJson(url)

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 他似乎想使用下一行中的承诺。所以如果他想要这个承诺,他可以删除await
    • 这是一个不错的选择。特别是如果你想使用 try 和 catch 和 finally
    猜你喜欢
    • 2020-10-03
    • 2018-08-18
    • 2022-06-18
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2019-11-03
    • 2020-09-07
    • 2019-09-12
    相关资源
    最近更新 更多