Guide on waiting for an asynchronous function in the constructor in JavaScript

In the process of creating a JS class, I encounter a situation where I need to call wasmFunc in the constructor and store its output in this.val. However, since wasmFunc comes from a WebAssembly file, it is necessary to execute an async function called loadWasm before wasmFunc becomes callable. The code snippet below demonstrates my attempt:

// index.js
async loadWasm() {
   // load wasm file
}

export class MyClass {
  constructor() {
    await loadWasm(); // This operation will not work
    this.val = wasmFunc();
  }
}

export const myObj = new MyClass();

My goal is for the exported file index.js to offer a ready-to-use myObj. Unfortunately, using await within the constructor is prohibited.

Do you have any solutions or thoughts on how to address this challenge?

Answer №1

  • Constructors are required to return an instance of the class being constructed
  • Asynchronous functions need to return a promise

Due to the fact that a function can only perform one task, it is not possible for a constructor function to be asynchronous.

Utilizing a Helper Function

A helper function can be used:

// index.js
async loadWasm() {
   // load wasm file
}

export class MyClass {
  constructor(wasm) {
    this.val = wasm;
  }
}

async function myClassFactory() {
    const wasm = await loadWasm();
    const instance = new MyClass(wasm);
    return instance;
}

You will need to await the result obtained from calling myClassFactory().

Storing a Promise in the Object

An alternative approach is to store a promise within the object created:

// index.js
async loadWasm() {
   // load wasm file
}

export class MyClass {
  constructor() {
    const wasmPromise = loadWasm();
    this.val = wasmPromise;
  }

  async doSomethingWithValue() {
    const wasm = await this.val;
    console.log(wasm);
  }
}

Answer №2

class MyNewClass {
    async constructor() {

    }
}

-> Uncaught SyntaxError: Class constructor may not be an async method

Edit: However, there is a workaround.

class MyNewClass {
    constructor(args) {
        this.arguments = args;
    };
    static async create(...args) {
        return new this(args);
    }
}
-> MyNewClass.create("test")

Answer №3

class CustomClass {
    async loadWebAssembly() {

    }

    async executeFunction(){
        await this.loadWebAssembly(); // This won't work
        this.value = wasmFunction();
    }

  constructor() {
    this.executeFunction()
  }
}

export const customObject = new CustomClass();

Give this a shot. It's worth a try.

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

When the checkbox is not selected, the content on the page will revert back to its original state

Is there a way to dynamically change content on a page when a checkbox is checked, and revert it back when the checkbox is unchecked? I don't want to manually set each element's value to default in JavaScript and CSS. <div class="switch&q ...

Show data from an API in an HTML table

I encountered an issue with an API, and despite trying console.log(response.[""0""].body) to view the response in the console, it does not seem to be working. My goal is to extract all the data from the API and display it in a table. Below is my code: ...

How can I allow users to select multiple files with just one input?

Currently, I am able to retrieve a single file from a single input using the following code: $scope.$on("fileSelected", function (event, args) { $scope.$apply(function () { $scope.files.push(args.file); ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Asynchronous update of array elements - lack of firing watch events

I have recently developed a component that showcases previews of blog articles. This particular component includes pagination functionality, where selecting a new page triggers the refreshment of the article previews array. The list of articles is obtained ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

I can't figure out why I keep getting the error message saying that $ is not

Looking to execute a PHP file using AJAX, I attempted the following: <html> <script type="text/javascript"> setInterval(function(){ test(); },3000); function test(){ $.ajax({ type: "POST", url: "GetMachineDetail.php", data: ...

Retrieving object key value from an array using Underscore.js

Hey there, I'm facing a challenge where I need to extract the values of wave1 and wave2 from an array using underscore.js. array = [{"id":1,"name":"Monoprix", "pdv":16,"graph":[{"wave1":22,"wave2":11}]} ; I attempted the following: $scope.wave1 = a ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

If the variable is not defined, then utilize a different one

There are two scopes: $scope.job and $scope.jobs. I also have a variable called job; If $scope.job is undefined, I want $scope.jobs to be assigned to the job variable using the following code: var job = $scope.jobs. However, if $scope.job is defined, the ...

AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes. Everything works fine if I define the language in the view beforehand, but when I t ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

What is the proper way to delete a callback from a promise object created by $q.defer() in AngularJS?

When working with AngularJS, the $q.defer() promise object has the ability to receive multiple notify callbacks without overwriting previous ones. var def = $q.defer(); def.promise.then(null, null, callback1); def.promise.then(null, null, callback2); If ...

What could be causing the 'Invalid element type' error to occur in my React Native application?

`import { StyleSheet, Text } from 'react-native'; import { Provider } from 'react-redux'; import { store } from './store'; import { HomeScreen } from './screens/HomeScreen'; import { SafeAreaProvider } from 'rea ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Transform socket.on into a promise

Currently, I am developing a service that involves the function init acting as resolve. Initially, it generates a folder using the connection's id and then proceeds to write some default files inside this newly created folder. The main goal here is to ...

Analyze items in two arrays using JavaScript and add any items that are missing

I am working on a JSON function that involves comparing objects in two different arrays, array1 and array2. The goal is to identify any missing items and either append them to array2 or create a new array called newArray1. Here is an example: const arra ...

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...