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

如何解决JavaScript中Await关键字引发的语法错误?

解决Node.js中await引发的SyntaxError错误

错误原因

await 关键字仅能在标记为async的函数内部,或者模块的顶层作用域中使用。你的helloWorld是普通箭头函数,未添加async修饰,直接使用await触发了语法错误。

修复步骤

将helloWorld函数修改为async箭头函数,同时补充响应处理逻辑(原代码未返回结果,部署后也无法正常工作):

修改后的完整代码

exports.helloWorld = async (req, res) => { // 添加async关键字
  const { Configuration, OpenAIApi } = require("openai");

  const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);

  try {
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      temperature: 0,
      max_tokens: 100,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["\n"],
    });
    // 返回OpenAI的响应结果
    res.status(200).send(response.data.choices[0].text.trim());
  } catch (error) {
    // 捕获并返回错误信息
    res.status(500).send({ error: error.message });
  }
};

关键改动说明

  • 在函数定义前添加async关键字:async (req, res) =>,让函数成为async函数,允许内部使用await。
  • 增加try/catch块:处理OpenAI API调用可能出现的异常,避免未处理的Promise rejection导致服务崩溃。
  • 补充响应逻辑:根据API调用结果返回成功响应或错误信息,确保接口能正常返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:50:20