首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待构造函数完成?

如何等待构造函数完成?
EN

Stack Overflow用户
提问于 2020-10-06 23:59:08
回答 1查看 238关注 0票数 0

我有一个具有异步元素的类构造函数。稍后,当我创建这个类的实例时,我想读取一个仅在构造函数完成100%时才存在的属性。我总是遇到问题Can not read property 'id' of undefined.,我几乎可以肯定这是一个关于异步的问题。等着吧。

代码语言:javascript
复制
    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();
        }
        ...
   }

稍后,我创建了这个类的一个实例,如下所示:

代码语言:javascript
复制
(async () => {
    const NPP = new NewPiecePlease;
    console.log(NPP.piecesDb.id);
    // This will give 'undefined' error
})();

我如何告诉NodeJS我希望new NewPiecePlease完全完成?await console.log(NPP.piecesDb.id);没有帮助,这是可以理解的,因为它不会理解我等待的是什么。执行此操作的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-07 00:16:39

你可以使用一个工厂来做这件事。它们非常适合创建复杂的、潜在的异步对象,并保持构造函数的整洁和专注。

代码语言:javascript
复制
 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方法执行所有的异步操作,并将结果传递给构造函数,在构造函数中,除了赋值和验证一些参数之外,它实际上不需要做任何事情。

代码语言:javascript
复制
(async () => {
    const NPP = await NewPiecePlease.create(IPFS, OrbitDB);
    console.log(NPP.piecesDb.id);
    // This will give 'undefined' error
})();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64229558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档