Merge pull request #27 from ChainSafe/init-with-promise
Cache a promise for Bls instead of Bls
This commit is contained in:
commit
fd196c56e2
|
@ -1,22 +1,34 @@
|
||||||
/* eslint-disable require-atomic-updates */
|
/* eslint-disable require-atomic-updates */
|
||||||
import blsWasmWrapper from "@chainsafe/eth2-bls-wasm";
|
import bls from "@chainsafe/eth2-bls-wasm";
|
||||||
|
|
||||||
let blsWrapper: typeof blsWasmWrapper | null = null;
|
type Bls = typeof bls;
|
||||||
|
let blsGlobal: Bls | null = null;
|
||||||
|
let blsGlobalPromise: Promise<Bls> | null = null;
|
||||||
|
|
||||||
export async function init(): Promise<typeof blsWasmWrapper> {
|
export async function setupBls(): Promise<Bls> {
|
||||||
if(blsWrapper) return blsWrapper;
|
if (!blsGlobal) {
|
||||||
await blsWasmWrapper.init();
|
await bls.init();
|
||||||
blsWrapper = blsWasmWrapper;
|
blsGlobal = bls;
|
||||||
return blsWrapper;
|
}
|
||||||
|
return blsGlobal;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache a promise for Bls instead of Bls to make sure it is initialized only once
|
||||||
|
export async function init(): Promise<Bls> {
|
||||||
|
if (!blsGlobalPromise) {
|
||||||
|
blsGlobalPromise = setupBls();
|
||||||
|
}
|
||||||
|
return blsGlobalPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function destroy(): void {
|
export function destroy(): void {
|
||||||
blsWrapper = null;
|
blsGlobal = null;
|
||||||
|
blsGlobalPromise = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getContext(): typeof blsWasmWrapper{
|
export function getContext(): Bls {
|
||||||
if(blsWrapper) {
|
if (!blsGlobal) {
|
||||||
return blsWrapper;
|
throw new Error("BLS not initialized");
|
||||||
}
|
}
|
||||||
throw new Error("BLS not initialized");
|
return blsGlobal;
|
||||||
}
|
}
|
Reference in New Issue