【问题标题】:cannot use await despite using an async function in codepen尽管在 codepen 中使用了异步函数,但无法使用 await
【发布时间】:2022-08-10 06:35:45
【问题描述】:

所以我在codepen中运行了确切的代码,但它给了我一个错误,尽管函数是异步的,但我不能使用await?我试图让 Javascrypt 等到从链接返回数据。

const url =
  \"https://raw.githubusercontent.com/ninjaboy667/RandomQuote/main/quotes_list.json\";

const getQuotes = async function () {
  return fetch(url)
    .then((response) => {
      return response.json();
    })
    .catch((error) => console.log(`error occurred ${error}`));
};

const { quotes } = await getQuotes();
console.log(quotes)

    标签: jquery getjson


    【解决方案1】:

    解决方案:

    此时的 Codepen不允许顶级等待,尽管方法(例如 fetch)是异步。

    一种解决方案是将整个 js 文件包装在异步函数中或使用 .then() 方法。

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多