Lazily load ModulePromise, make rethrowIfCritical standalone

This commit is contained in:
ICheered
2023-08-04 14:15:01 +02:00
parent 8c21f708be
commit d0841c4c85

View File

@@ -33,23 +33,7 @@ async function initializeModule() {
} }
} }
const ModulePromise = initializeModule().then(initModule => { export function rethrowIfCritical(err) {
if (initModule) {
return initModule();
} else {
return null;
}
});
class Camera {
constructor() {
/** @type {Promise<unknown>} */
this.queue = Promise.resolve();
this.Module = null;
this.context = null;
}
rethrowIfCritical(err) {
// If it's precisely Error, it's a custom error; anything else - SyntaxError, // If it's precisely Error, it's a custom error; anything else - SyntaxError,
// WebAssembly.RuntimeError, TypeError, etc. - is treated as critical here. // WebAssembly.RuntimeError, TypeError, etc. - is treated as critical here.
if (err.constructor !== Error) { if (err.constructor !== Error) {
@@ -57,8 +41,26 @@ class Camera {
} }
} }
class Camera {
constructor() {
/** @type {Promise<unknown>} */
this.queue = Promise.resolve();
this.Module = null;
this.context = null;
this.ModulePromise = null;
}
async connect() { async connect() {
this.Module = await ModulePromise; if (!this.ModulePromise) {
this.ModulePromise = initializeModule().then(initModule => {
if (initModule) {
return initModule();
} else {
return null;
}
});
}
this.Module = await this.ModulePromise;
this.context = await new this.Module.Context(); this.context = await new this.Module.Context();
} }
@@ -69,7 +71,7 @@ class Camera {
*/ */
async schedule(op) { async schedule(op) {
let res = this.queue.then(() => op(this.context)); let res = this.queue.then(() => op(this.context));
this.queue = res.catch(this.rethrowIfCritical); this.queue = res.catch(rethrowIfCritical);
return res; return res;
} }