You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Codepen中使用async函数仍无法使用await的问题排查

问题分析与解决

你的代码报错是因为**await只能在async函数内部,或者ES模块的顶层作用域中使用**,而你在普通脚本的顶层直接调用了await getQuotes(),不符合语法规则。

解决方案1:将顶层代码包裹在async函数中

把需要使用await的代码放到一个自定义的async函数里,然后调用这个函数执行:

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

// 推荐用await/try-catch替代then链,更符合async函数的写法
const getQuotes = async function () {
  try {
    const response = await fetch(url);
    return response.json();
  } catch (error) {
    console.log(`error occurred ${error}`);
    // 出错时返回默认值,避免后续解构报错
    return { quotes: [] };
  }
};

// 封装顶层逻辑到async函数
async function loadQuotes() {
  const { quotes } = await getQuotes();
  console.log(quotes);
}

// 执行函数
loadQuotes();

解决方案2:切换到ES模块模式

如果Codepen支持ES模块,你可以在JavaScript设置里将脚本类型改为Module,这样就能在顶层直接使用await,代码无需大改:

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

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

// 模块模式下可直接在顶层用await
const { quotes } = await getQuotes();
console.log(quotes);

额外注意点

  • 原代码中getQuotes的catch块仅打印错误,未返回任何值,一旦请求失败,await getQuotes()会得到undefined,后续解构quotes会抛出新错误。建议在catch中返回一个包含空quotes的默认对象,避免后续逻辑崩溃。

内容的提问来源于stack exchange,提问作者ninjaboy667

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:54:52