Issue with loading Three.js asynchronously

My attempt to determine the maximum value of a point cloud data using the following code proved unsuccessful.

import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader";

let max_x = -Infinity;

function initModel() {
  new PLYLoader().load("../data/division/1.ply", (geometry) => {
    for (let j = 0; j < geometry.attributes.position.count; j += 3)
      max_x = Math.max(max_x, geometry.attributes.position.array[j]);
  });
}

function print() {
  console.log(max_x);
}

initModel();
print();//resulted in -Infinity

The issue arose because Three.js loaded the file asynchronously. Attempting to resolve it, I experimented with different solutions, such as adding async and await to the functions.

import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader";

let max_x = -Infinity;

async function initModel() {
  new PLYLoader().load("../data/division/1.ply", (geometry) => {
    for (let j = 0; j < geometry.attributes.position.count; j += 3)
      max_x = Math.max(max_x, geometry.attributes.position.array[j]);
  });
}

async function print() {
  await initModel();
  console.log(max_x);
}

print();//still resulted in -Infinity

Despite my efforts, the output remained -Infinity. I sought solutions online, but the examples I found did not involve handling data within the callback function of load like I did. Surprisingly, using setTimeout() proved to be effective. Any assistance would be greatly appreciated.

Answer №1

Upon your exploration, it was revealed that the file is being loaded in an asynchronous manner. However, your revised code still fails to function correctly due to the fact that while initModel() is now asynchronous, it does not await the completion of load(); rather, it simply calls it and continues. Since PLYLoader.load() is not defined as an async function, you cannot simply await its execution.

I suggest delving into the realm of asynchronous JavaScript programming in order to enhance your understanding. The simplest approach would be to make your logic asynchronous as well, and utilize print() within the callback function, like so:

function initModel() {
    new PLYLoader().load("../data/division/1.ply", (geometry) => {
        for (let j = 0; j < geometry.attributes.position.count; j += 3)
            max_x = Math.max(max_x, geometry.attributes.position.array[j]);

        print();
    });
}

If you are determined to incorporate synchronous code, you could potentially await a promise that periodically checks whether your model has finished constructing. However, it is more likely that you would prefer to execute other tasks in the meantime rather than suspending your program's progress. There are usually methods to adapt your program's logic to work seamlessly with asynchronous processes, and this approach is usually more advantageous.

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 make a global call to an asynchronous function: "The use of 'await' is restricted to async functions and the top level bodies of modules."

As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite ali ...

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Three.js implementation of a 2D scatter plot

I experimented with Three.js to create a 3D scatter plot. Take a look at this demo I created on jsFiddle... http://jsfiddle.net/jmg157/ynFzw/19/ I randomly generated some points (x, y, z) and added them to the plot. This is the loop I used for this task: ...

Incorporate the ng2-ace library into a newly generated Angular-CLI (Angular2) project with the help of SystemJS

After setting up my angular2 project using the latest angular-cli tool, I decided to integrate the ace editor with the help of the ng2-ace library. My goal was to implement this in a clean manner using SystemJS as the module loader. I started by running ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

NodeJS - session information lost after building ReactJavaScript application

I've created a NodeJS web application with basic functionality for user login and pulling data from MySql based on session information. The app is functioning as intended (Link). However, when I implement the client-side in React, the session data is ...

Managing data from two tables in Node.js with ejs

I have a question regarding my node.js project that I need help with. As a beginner in this field, I believe the answer may be simpler than anticipated. In my code file named index.js, I found the following snippet after referring to some online documenta ...

Dynamic popup in RShiny interface with the ability to be moved around

I am currently working on a dashboard project and I am looking to implement a dynamic popup feature that can be moved around. I have been able to create a pop-up, but it remains static. I would like the flexibility for users to drag and position the popup ...

Compatibility of image maps with browsers and the usage of imagemapster

Currently, I am utilizing ImageMapster to make adjustments to an image map while hovering. However, I am facing challenges with both the image map itself and the ImageMapster plugin. The issues I am encountering are: 1) Despite specifying a height and wid ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Retain selected elements and eliminate the rest while maintaining structure with Cheerio/jQuery

I am looking to isolate specific elements while maintaining their structure. For example: <html> <head> <meta xx> </head> <body> <div class="some1"> <div class="some1-1">< ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Improving React Components with Material-UI Integration

Is it possible to export a class extended from React.Component while using React and Material-UI? I need to access React variables like state within the class. If exporting the extended class is not an option, how can I still utilize state? Here is a samp ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

Exploring how to alter state in a child component using a function within the parent component in React

class ParentComponent extends Component { state = { isDialogOpen: false, setStyle: false } handleClose = () => { this.setState({ isDialogOpen: false, setStyle: false }) } handleOpen = () => { this.setState({ isDialogOpen: true ...

Tips for preserving an HTML dynamic table in a database

I have a challenge where I am generating a dynamic HTML table using javascript. What is the best way to store this dynamic HTML table in a database using CodeIgniter? This is the code snippet for my input form: <table id="tb3" name="tb3"> & ...

Troubleshooting problem with AJAX returning JSON values

Utilizing a jQuery post request in the following manner: $.post('url', {data: some_data}, function(data, textStatus, jqXHR) { console.log(data); //for debugging console.log(data.status == "ok"); //for debugging .... }); The url hits ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...