在导出的类中使用异步js导入

问题描述 投票:0回答:1

给出公开异步/动态导出的包。我目前以这种方式导入(但是我可以采用其他方式导入):

(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();
  }
}

我该怎么办?


更多信息:

  • 公开异步/动态导出的包是由webpack打包webassembly生成的。我不确定是否可以更改此部分的任何内容
  • 我肯定可以更改导入该软件包的方式
  • 我也可以更改重新暴露/分组功能的方式(并使用除类之外的其他方式)
javascript typescript class dynamic-import
1个回答
0
投票

我有几种方法可以解决这个问题:

  1. 如果不需要立即实例化该类,那么我将等待库加载,然后将其传递给类构造函数。这是最干净的方法,因为总是在类中定义库。

  2. 如果必须在提取库之前实例化该类,则该类中的方法必须处理未定义的情况(例如,尚未加载)。然后,您可以调用类似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();
}
© www.soinside.com 2019 - 2024. All rights reserved.