【问题标题】:Declaring an async function in an existing object在现有对象中声明异步函数
【发布时间】:2020-03-31 16:31:00
【问题描述】:

这是我已经拥有的:

myFunct({ myObj: { db } })

我需要添加另一个功能,例如:

myFunct({ myObj: async ({ req }) => {
  //more scripts
} })

我尝试过但失败了:

myFunct({ myObj: {
  db,
  async (req) => {
    //more scripts
  }
} })

在 => 我得到语法错误:

Unexpected token, expected {

【问题讨论】:

  • 它不起作用,因为您没有命名将保存该函数的属性。 { db } 语法是声明与标识符同名的属性用作值的简写,例如:{ db: db }
  • 我知道这很容易被我忽略。尝试将我的编程语言从 php 切换到 node 带来了一系列挑战。

标签: javascript function ecmascript-6 async-await syntax-error


【解决方案1】:

您必须提供属性名称。

如果你有一个变量,它可以作为属性名和值。

const myFunction = async (req) => {
    //more scripts
};

myFunct({ myObj: {
  db,
  myFunction
} })

如果你只有一个值,那么你需要明确地声明属性名称。

myFunct({ myObj: {
  db,
  myFunction: async (req) => {
    //more scripts
  }
} })

【讨论】:

  • 或者替代第二个示例async myFunction (req) { ... },尽管this 的行为会有所不同。
  • @PatrickRoberts 有什么不同?刚接触 async-await,你能指导我解释一下吗?
【解决方案2】:

您没有为您的功能提供密钥:

试试:

myFunct({
  myObj: {
    db,
    yourKey: async (req) => {
      //more scripts
    }
  }
})

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 2018-06-03
    • 1970-01-01
    • 2020-11-25
    • 2023-03-10
    • 1970-01-01
    • 2016-05-20
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多