[英]Using async js imports in exported classes
给定一个公开异步/动态导出的包。 我目前以这种方式导入(但我可以以不同的方式导入):
(async function() {
const libEd = await import("../../.cache/ed25519wars/index.js");
})();
我打算将libEd
一些函数作为类的一部分重新公开:
export class Something {
static from_X() {
return libEd.genFromX();
}
do_Y() {
return libEd.doY();
}
}
我怎样才能做到这一点 ?
欲了解更多信息:
我有几种方法可以解决这个问题:
如果类不需要立即实例化,那么我将等待库加载,然后将其传递给类构造函数。 这是最简洁的方式,因为库总是在类中定义。
如果在获取库之前必须实例化类,则类中的方法必须处理未定义(例如尚未加载)的情况。 然后您可以调用类似await myClassInstance.init()
来获取库。 如果库尚未加载,我通常会为每个方法提供一个回退,也许它返回一个空字符串或一个虚拟 UI。
编辑:为选项 1 添加 TypeScript 示例
interface MyLibrary {
libraryMethod: () => void;
}
class ExampleClass {
localLib: MyLibrary;
constructor(lib: MyLibrary) {
this.localLib = lib;
}
myClassMethod() {
this.localLib.libraryMethod();
}
}
async function run() {
// first we fetch the remote library
const myLibrary: MyLibrary | undefined = await import('/lib.js');
// good practise to add some check here
if (!myLibrary) {
throw Error('failed to fetch myLib');
}
// then we create the class instance using the downloaded library
const myClassInstance = new ExampleClass(myLibrary);
// now we can call our class method which definitely has the remote library
myClassInstance.myClassMethod();
}
我最终选择了三种方法之一:
@Tim 的方法(接受的答案):在类属性中包含导入,并在构造函数时await
。
但是:可能存在与在每个实例中存储导入相关的开销。
await
在类的每个方法中定义导入:export class Something {
static async from_X() {
const libEd = await loadLibProm();
return libEd.genFromX();
}
async do_Y() {
const libEd = await loadLibProm();
return libEd.doY();
}
}
但是:类 API 现在都是异步的,使用起来更尴尬。
let libEd: typeof import("../../.cache/ed25519wars/index.js");
async function loadLibProm(): Promise<
typeof import("../../.cache/ed25519wars/index.js")
> {
libEd = await import("../../.cache/ed25519wars/index.js");
return libEd;
}
loadLibProm(); // this somehow starts running the promise ?? wut ? Anyways that's what we want
export class Something {
static from_X() {
return libEd.genFromX();
}
do_Y() {
return libEd.doY();
}
}
但是:对于在导入完成之前/导入失败之后创建类的实例的情况,这需要更好的错误处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.