【问题标题】:async arrow function SyntaxError: Unexpected token (异步箭头函数 SyntaxError: Unexpected token (
【发布时间】:2019-08-07 01:17:55
【问题描述】:

我在 Windows pc 上使用节点版本 10.15.3、npm 版本 6.9.0、VS 代码和 firebase-functions 版本 2.2.0。将 async/await 添加到我的 app.post() 函数会导致:

 Function failed on loading user code. Error message: Code in file 
 index.js can't be loaded.
 Is there a syntax error in your code?
 Detailed stack trace: /user_code/index.js:31
 app.post('/pay-now', async (req, res) => {
                       ^

 SyntaxError: Unexpected token (
     at createScript (vm.js:56:10)
     at Object.runInThisContext (vm.js:97:10)
     at Module._compile (module.js:549:28)
     at Object.Module._extensions..js (module.js:586:10)
     at Module.load (module.js:494:32)
     at tryModuleLoad (module.js:453:12)
     at Function.Module._load (module.js:445:3)
     at Module.require (module.js:504:17)
     at require (internal/module.js:20:19)
     at getUserFunction (/var/tmp/worker/worker.js:439:24)

这是我的 app.post():

app.post('/pay-now', async (req, res) => {
    // charge user's card
    const charge = await makeCharge(req, res)
    // store order info in database, returns address of order
    const address = await storeOrder(req, res, charge.id)
    // send email to customer
    await emailHandler.sendCustomerEmail(req, res)
    // send email to company letting them know they have a new order
    await emailHandler.sendLTEmail(req, res, address, true)
    return res.sendStatus(200)
})

我尝试删除 app.post() 中的 async 和 await,但是在函数 makeCharge 中第一次使用 async 时我得到了同样的错误。知道什么可能是错的吗?

【问题讨论】:

  • 您是否尝试过删除node_modules 目录后跟npm install?也许您最近更改了节点版本,并且您的模块是使用不同版本构建的?
  • 你到底做了什么(运行命令?在编辑器中做某事?)使错误出现?
  • @Robbie 刚刚尝试过并得到了相同的结果
  • @DougStevenson 我运行firebase deploy --only functions

标签: node.js firebase express npm async-await


【解决方案1】:

也许你应该看看这里:Syntax for async arrow function

你的模块没有问题,我觉得箭头函数写得不好。

编辑:

我对箭头函数不太了解,你能尝试使用“普通函数”吗:

  app.post('/pay-now', async function Myfunction (req, res) {
  // do something
}

【讨论】:

  • 似乎对我不起作用,箭头会产生语法错误
  • 31:48 error Parsing error: Unexpected token, expected "{"上线app.post('/pay-now', async function (req, res) => {
  • 嗯,那不知道,能不能不用箭头函数?并尝试“正常”功能?这行得通吗?
  • @DougStevenson 的回答能够解决问题,不过感谢您的帮助!
【解决方案2】:

目前,Cloud Funtions 的默认运行时是节点 6,不支持异步/等待。您需要将您的 package.json 编辑为 target the node 8 runtime,它使用具有 async/await 的 JavaScript 版本。

通过在 package.json 文件中添加引擎字段来设置版本 它是在初始化期间在您的函数/目录中创建的。 例如,如果您更喜欢仅使用版本 8,请将 package.json 编辑为 添加这一行:

"engines": {"node": "8"}

如果您已经部署了某个版本的功能,则需要在此配置到位后将其删除并重新部署。

【讨论】:

  • 对我来说这不是问题。我在 v14 的节点上。
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 2019-02-10
  • 2019-11-10
  • 2014-07-08
  • 2013-11-15
相关资源
最近更新 更多