Utilizing asynchronous JavaScript imports within exported classes

Currently, I have a package with async/dynamic exports that I import in the following manner:

(async function() {
  const libEd = await import("../../.cache/ed25519wars/index.js");
})();

I plan to re-expose certain functions from libEd within a class structure:

export class Something {
  static from_X() {
    return libEd.genFromX();
  }

  do_Y() {
    return libEd.doY();
  }
}

How can I achieve this?


Additional Information:

  • The package with async/dynamic exports is created using webpack to pack webassembly. I am unsure if modifications can be made to this aspect.
  • I have the flexibility to modify how I import the package.
  • We can also explore alternative methods to re-expose/group the functions instead of using a class.

Answer №1

Approaching this situation can be done in a couple of ways:

  1. If there is no immediate need for the class instantiation, waiting for the library to load and then passing it to the class constructor would be the cleanest method. This ensures that the library is always defined within the class.

  2. In cases where the class needs to be instantiated before fetching the library, methods within the class should handle scenarios when the library is not yet defined or loaded. To address this, you can use something like await myClassInstance.init() to retrieve the library. It is advisable to provide fallbacks for each method if the library is not loaded yet, such as returning an empty string or a dummy UI.

EDIT: A TypeScript example for option 1 has been added below:

interface MyLibrary {
  libraryMethod: () => void;
}

class ExampleClass {
  localLib: MyLibrary;

  constructor(lib: MyLibrary) {
    this.localLib = lib;
  }

  myClassMethod() {
    this.localLib.libraryMethod();
  }
}

async function run() {
  // Fetching the remote library first
  const myLibrary: MyLibrary | undefined = await import('/lib.js');

  // Adding a check for good practice
  if (!myLibrary) {
    throw Error('failed to fetch myLib');
  }

  // Creating an instance of the class using the downloaded library
  const myClassInstance = new ExampleClass(myLibrary);

  // Calling the class method knowing that the remote library is now available
  myClassInstance.myClassMethod();
}

Answer №2

After considering various options, I narrowed it down to three possible methods:

  1. Following @Tim's method (which is the accepted answer): include the import in the class properties and use await at constructor time.

    However, there may be a downside of overhead associated with storing the import in each instance.


  1. awaiting in each method of the class to define the import locally:
export class Something {
  static async from_X() {
    const libEd = await loadLibProm();
    return libEd.genFromX();
  }

  async do_Y() {
    const libEd = await loadLibProm();
    return libEd.doY();
  }
}

Yet this results in the class API being entirely asynchronous and more cumbersome to work with.


  1. Pre-loading the import at the start of the code and assuming that the loading will be completed when the class is called.
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();
  }
}

Nonetheless, this approach requires improved error handling for cases where an instance of the class is created before the import is completed or after the import fails.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...

Challenges with the efficiency of the Material UI Datagrid

I am currently using MUI Datagrid to display my records, but I am experiencing delays with my modal and drawer components. Even after attempting to optimize with useMemo for my columns, I have not been able to achieve satisfactory performance. https://i.st ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...

Error message: Could not locate the class 'NunoMaduroCollisionAdaptersLaravelCollisionServiceProvider'

Encountering an error while attempting to install Composer in a Laravel project. Error message: Illuminate\Foundation\ComposerScripts::postAutoloadDump @php artisan package:discover In ProviderRepository.php line 208: Class 'NunoMadur ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Uploading base64 arrays from AngularJS to a Node.js server: Allowing Access-Control-Origin

My current challenge involves sending an array of base64 strings from my Client Side (AngularJs) to my NodeJs Server. However, I've encountered a peculiar situation. When I attempt to send an object containing the base64 data along with other properti ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Issue with SetTimeout not functioning properly on initial use within socket.io

Currently, I am trying to come up with a method to retrieve an IP address from a node server that is hosted on a dynamic IP. The issue I am facing is that the setTimeout function does not seem to work properly on the server side during the initial launch. ...

Utilizing Jade to access and iterate through arrays nested in JSON data

Take a look at this JSON data: { "Meals": { "title": "All the meals", "lunch": ["Turkey Sandwich", "Chicken Quesadilla", "Hamburger and Fries"] } } I want to pass the array from this JSON into a jade view so that I can iterate over each item in ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Is it possible to have an array as a subclass of a single superclass in C

My goal is to recreate a deck of cards by utilizing two classes, specifically "class Deck" and "class Card : public Deck". In the /deck/ class, I am aiming to create a function that will set up the 52 cards in an array while maintaining their order. Additi ...

Split the string in JavaScript and then count the characters to decrypt

I am currently working on a task that involves splitting a string at every space. I have successfully achieved this using .split(" "), but now I need to determine the length of each individual string. My goal is to check if a given string includes a midd ...

Utilizing the Squared² Symbol in the Jscript File Path for Execution

I am encountering an issue with launching applications on a corporate portal that are tied to a specific business group. The problem arises when trying to access a file path that includes a ² character. This software is widely used on over 3000 computers ...

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

Having trouble with form validation in React.js? Wondering about the best ways to compare two fields? Let's

It's important to ensure that users enter the same email in both the email and confirmEmail input fields. I've experimented with a few methods, but I'm not certain of the best approach. Is there a simpler way that I might be overlooking? In ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Differences between Creating and Updating Objects in JavaScript

When working with JavaScript, it is important to consider the best practices for performance optimization. Take a look at these two examples: Example 1: var x = {}; x.a = 10; Example 2: var x = {}; x = {a: 10}; Are there any noticeable differences in ...

What is the best way to combine the elements of two arrays within a v-for loop?

Within my code, I have defined two arrays: users and projects. Each array contains unique numbers as IDs. A project can be owned by multiple users, so in the projects array, there is an array of user IDs named ownersId that corresponds to the id of users i ...