为了账号安全,请及时绑定邮箱和手机立即绑定

如何等待构造函数完成?

如何等待构造函数完成?

潇潇雨雨 2023-04-20 09:56:19
我有一个具有异步元素的类构造函数。稍后当我创建此类的实例时,我想读取一个仅在构造函数完成 100% 时才存在的属性。我总是遇到问题Can not read property 'id' of undefined.我几乎可以肯定这是关于异步的问题..等待。    class NewPiecePlease {        constructor(IPFS, OrbitDB) {             this.OrbitDB = OrbitDB;                (async () => {                this.node = await IPFS.create();                        // Initalizing OrbitDB                this._init.bind(this);                this._init();            })();        }            // This will create OrbitDB instance, and orbitdb folder.        async _init() {            this.orbitdb = await this.OrbitDB.createInstance(this.node);            console.log("OrbitDB instance created!");                this.defaultOptions = { accessController: { write: [this.orbitdb.identity.publicKey] }}                const docStoreOptions = {                ...this.defaultOptions,                indexBy: 'hash',            }            this.piecesDb = await this.orbitdb.docstore('pieces', docStoreOptions);            await this.piecesDb.load();        }        ...   }后来我像这样创建了这个类的一个实例:(async () => {    const NPP = new NewPiecePlease;    console.log(NPP.piecesDb.id);    // This will give 'undefined' error})();我如何告诉 NodeJS 我想new NewPiecePlease完全完成?await console.log(NPP.piecesDb.id);没有帮助,这是可以理解的,因为它不会理解我在等待什么。这样做的正确方法是什么?
查看完整描述

1 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

您可以为此使用工厂。它们非常适合进行复杂的、潜在的异步对象创建,并使您的构造函数保持干净和专注。


 class NewPiecePlease {

  constructor(orbitdb, node, pieceDB) {

    this.orbitdb = orbitdb;

    this.node = node;

    this.pieceDB = pieceDB;

  }

  

  static async create(IPFS, OrbitDB) {

    const node = await IPFS.create();

    const orbitdb = await OrbitDB.createInstance(node);

    console.log("OrbitDB instance created!");


    const defaultOptions = {

      accessController: {

        write: [orbitdb.identity.publicKey]

      }

    }


    const docStoreOptions = { ...defaultOptions, indexBy: 'hash' };

    const piecesDb = await orbitdb.docstore('pieces', docStoreOptions);

    

    await piecesDb.load();

    

    return new NewPiecePlease(orbitdb, node, piecedb);

  }

}

如您所见,create 方法执行所有异步操作,并将结果传递给构造函数,在构造函数中它实际上不需要执行任何操作,除了分配和可能验证一些参数。


(async () => {

    const NPP = await NewPiecePlease.create(IPFS, OrbitDB);

    console.log(NPP.piecesDb.id);

    // This will give 'undefined' error

})();


查看完整回答
反对 回复 2023-04-20
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信