如何等待构造函数完成?

时间:2020-10-06 15:59:07

标签: javascript asynchronous async-await

我有一个具有异步元素的类构造函数。稍后,当我创建此类的实例时,我想读取一个仅在构造函数完成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 个答案:

答案 0 :(得分:1)

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

 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
})();