我正在尝试在类构造函数中使用ES6解构,但遇到未知的令牌错误。这是一个例子:

// import / server / a-and-b.js

class A {
  constructor(id) {
    // make MongoDB call and store inside this variable
    let {
      firstName: this._FirstName // => Throws here
    } = CollectionName.findOne({userId: id});
  }
}

export class B extends A {
  constructor(id) {
    super(id);
  }
  get FirstName() {
    return this._FirstName;
  }
}


// import / server / test.js

import { B } from 'imports/server/a-and-b.js'

const b = new B('123')

const FirstName = b.FirstName;


相同的解构将在课堂外起作用:

// another-test.js

// make MongoDB call and store inside this variable
let {
  firstName: FirstName // works fine
} = CollectionName.findOne({userId: id});

最佳答案

您的语法不正确。您试图做的事是不可能的。假设findOne方法是同步的,则需要执行以下操作:

constructor(id) {
    // make MongoDB call and store inside this variable
    let { firstName } = CollectionName.findOne({userId: id});
    this._FirstName = firstName;
  }

09-20 19:10