Merge pull request #27 from ChainSafe/init-with-promise

Cache a promise for Bls instead of Bls
This commit is contained in:
Cayman 2020-11-04 10:24:27 -07:00 committed by GitHub
commit fd196c56e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 12 deletions

View File

@ -1,22 +1,34 @@
/* 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> {
if(blsWrapper) return blsWrapper;
await blsWasmWrapper.init();
blsWrapper = blsWasmWrapper;
return blsWrapper;
export async function setupBls(): Promise<Bls> {
if (!blsGlobal) {
await bls.init();
blsGlobal = bls;
}
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 {
blsWrapper = null;
blsGlobal = null;
blsGlobalPromise = null;
}
export function getContext(): typeof blsWasmWrapper{
if(blsWrapper) {
return blsWrapper;
}
export function getContext(): Bls {
if (!blsGlobal) {
throw new Error("BLS not initialized");
}
return blsGlobal;
}