如何解决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
相关产品推荐
相关产品推荐

