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

Apollo Server启动报错:await不能在async函数外部使用

解决Apollo Server启动时"await不能在async函数外部使用"的错误

错误原因很明确:JavaScript中await关键字仅允许在被async修饰的函数内部使用,你当前直接在全局作用域调用await startStandaloneServer(server),违反了这个语法规则。

修正后的代码如下:

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

import { typeDefs } from "./schema.js";
import db from "./_db.js";

const resolvers = {
  Query: {
    games() { return db.games },
    reviews() { return db.reviews },
    authors() { return db.authors }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers
});

// 将启动逻辑包裹在async函数内
async function startServer() {
  const { url } = await startStandaloneServer(server);
  console.log("Server started at:", url);
}

// 执行启动函数
startServer();

补充说明:

  • 用async函数包裹后,await就能合法调用异步的startStandaloneServer方法
  • 建议直接打印返回的url而非硬写端口4000,因为如果默认端口被占用,Apollo Server会自动切换可用端口,返回的url会包含实际使用的端口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:07:05