When you try to load data in THREE.js and add it to a list, the list does not get populated

When running my data, I utilize the following function:

function loadData(){
    const loader = THREE.FileLoader();
    let loadedData = [];
    loader.load( correctFileUrl,
        function (data) {
            console.log(data);
            for (let row of data.split('\n'))
            {
                loadedData.push(row);
            }
        },
        function (xhr) {console.log(('Loaded data: ' + xhr.loaded / xhr.total * 100) + '% completed')},
        function(err)  {console.error(err)}
    );
    return loadedData;
}

In this scenario, correctFileUrl represents the accurate hashed URL of the file I wish to load (which is a simple CSV containing strings for each row). Despite being able to log the content of the file and confirming it is loaded correctly, the method consistently returns an empty list. As someone new to JavaScript, I'm puzzled as to why it's not functioning as anticipated.

Answer №1

Ensure that loading is asynchronous by utilizing a promise

function loadData(){
    return new Promise((resolve) => {
        let loadedData = [];
        loader.load(dataFileUrl,
            function (data) {
                console.log(data);
                for (let row of data.split('\n')) {
                    loadedData.push(row);
                }
                resolve(loadedData)
            },
            function (xhr) { console.log(('Loading data : ' + xhr.loaded / xhr.total * 100) + '% loaded') },
            function (err) { console.error(err) }
        );
    })
}

Implementing something similar to this approach should effectively address the issue at hand.

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

Ionic 2: Inconsistency detected in the expression after it was verified

After going through this response, this solution and this advice (as well as numerous others), I still find myself struggling to comprehend how to resolve this issue in my current approach. The task at hand involves creating an event countdown timer that ...

Incorporate a 404 Not Found redirect into the getServerSideProps method in Next.js

I'm seeking guidance on best practices for handling an HTTP 404 error in a server-side rendered page when the requested page lacks a corresponding server-side resource. For instance, let's say the requested page is http://localhost:3000/places/5 ...

Error: Surprising token found in ReactJS application on CodeSandbox

Encountering an unexpected token on line 5 error in my ReactJS project when testing it on CodeSandbox. Interestingly, the app runs smoothly without errors on my local machine. import React, { Component } from 'react'; import Header from ' ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Get rid of empty spaces in gridstack js

My latest project involves using gridstack js In the image displayed, I have highlighted the excess white space (in blue) that needs to be removed. Take a look at this visual: https://i.sstatic.net/Qgt62.jpg Any suggestions on how to eliminate this ...

Make sure to wait for the scrollTo function to finish before executing any other commands

I have a sleek scrolling directive in my AngularJS app that automatically scrolls to the bottom of the page. I want this command to execute only after the scrolling has completed. Currently, I trigger the scroll function and then use $('#comment-input ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

Encountering challenges with the angular2-infinite-scroll plugin

I encountered 2 errors while using my application: Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3002/angular2-infinite-scroll angular2-polyfills.js:1243 Error: XHR error (404 Not Found) loading htt ...

passing a PHP variable into an HTML input field

Recently, I've encountered a problem where I need to transfer PHP variables to HTML input fields. echo $ManuellTagnavnMain; for ($n = 0; $n < 6; $n++) { print_r(++$ManuellTagnavnMain.PHP_EOL); } I'm looking for a way to pass these values ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

Save the data retrieved from the success callback of a jQuery.ajax() request to be

Currently in my project, I am attempting to retrieve data from a PHP script. Most AJAX callback functions I have researched show examples where they "use" the data directly in the callback function itself. However, I am looking to fetch data and store it i ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Perform an action upon a successful completion of an AJAX request using Axios by utilizing the `then()` method for chaining

I'd like to trigger a specific action when an ajax call is successful in axios save() { this.isUpdateTask ? this.updateProduct() : this.storeProduct() this.endTask() } When the ajax call to update or store the product succeed ...

Having trouble with blockUI compatibility on Internet Explorer 11?

I have encountered an issue with a piece of code that functions correctly in Chrome and FF, but not in ie11. Interestingly enough, when I tested it in ie8, it worked perfectly fine. Has anyone else experienced similar problems with blockUI on ie11? The s ...