javascript - 如何等待构造函数完成?
问题描述
我有一个具有异步元素的类构造函数。稍后当我创建此类的实例时,我想读取一个仅在构造函数完成 100% 时才会存在的属性。我总是遇到问题Can not read property 'id' of undefined.
我几乎可以肯定这是关于 async .. await 的问题。
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);
没有帮助,这是可以理解的,因为它不会理解我在等待什么。这样做的正确方法是什么?
解决方案
您可以为此使用工厂。它们非常适合进行复杂的、潜在的异步对象创建,并保持构造函数的简洁和专注。
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
})();
推荐阅读
- sql - 如何在 PL/SQL 中创建一个以时间段递增的循环
- android - 在 Espresso 中,如何在不触发 AmbiguousViewMatcherException 的情况下对所有匹配视图执行操作?
- atlassian-sourcetree - 在 Sourcetree 中使用丢弃
- javascript - 根据 v-radio 选择使 v-text-field 成为必需
- javascript - React 中 document.getElementById("root").appendChild(node) 的等价物是什么?
- python - 在 Python 中删除特定字符/字符串/字符序列
- python - 有没有办法确定传递给函数的参数是在python中分配还是文字?
- python - 在excel中插入日期公式得到#name?用python插入后出错
- visual-studio - 重新启动 Shell Visual Studio
- reactjs - 使用 refs 从父组件向子组件 div 添加/删除类