1 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以為此使用工廠。它們非常適合進(jìn)行復(fù)雜的、潛在的異步對(duì)象創(chuàng)建,并使您的構(gòu)造函數(shù)保持干凈和專注。
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);
}
}
如您所見(jiàn),create 方法執(zhí)行所有異步操作,并將結(jié)果傳遞給構(gòu)造函數(shù),在構(gòu)造函數(shù)中它實(shí)際上不需要執(zhí)行任何操作,除了分配和可能驗(yàn)證一些參數(shù)。
(async () => {
const NPP = await NewPiecePlease.create(IPFS, OrbitDB);
console.log(NPP.piecesDb.id);
// This will give 'undefined' error
})();
添加回答
舉報(bào)