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

调用API时遇SyntaxError:await仅在async函数等场景有效

修复 "SyntaxError: await is only valid in async functions, async generators and modules" 错误

这个错误的核心原因很明确:await关键字只能在async函数、async生成器或者ES模块的顶层作用域中使用,你的代码直接在全局非async环境下使用了await,所以触发语法错误。

下面是两种可行的修复方式:

方式一:将代码包裹在async函数内

把你的fetch逻辑放到一个async函数里,然后调用这个函数即可:

const url = 'https://moviesdatabase.p.rapidapi.com/titles/search/keyword/%7Bkeyword%7D';
const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': '3065ca2efamsh5511818a494e23fp1cbb2cjsna2ae6a53946f',
        'X-RapidAPI-Host': 'moviesdatabase.p.rapidapi.com'
    }
};

async function fetchMovieData() {
    try {
        let response = await fetch(url, options);
        const result = await response.text();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

// 执行函数
fetchMovieData();

方式二:使用ES模块(浏览器环境适用)

如果是在浏览器中运行代码,给加载脚本的<script>标签添加type="module"属性,这样就能在顶层作用域直接使用await:

<script type="module">
const url = 'https://moviesdatabase.p.rapidapi.com/titles/search/keyword/%7Bkeyword%7D';
const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': '3065ca2efamsh5511818a494e23fp1cbb2cjsna2ae6a53946f',
        'X-RapidAPI-Host': 'moviesdatabase.p.rapidapi.com'
    }
};

try {
    let response = await fetch(url, options);
    const result = await response.text();
    console.log(result);
} catch (error) {
    console.error(error);
}
</script>

额外提醒

你的URL中包含%7Bkeyword%7D(URL编码后的{keyword}),这是一个占位符,记得替换成实际的搜索关键词(比如batman),否则API可能无法返回正确的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:16:12