Set a variable to store the loaded 3D object and receive an undefined value in return

I've been working on a function to load 3D objects using three.js.

My goal is for this function to return the 3D object once it's loaded, but no matter what I try, I keep getting "undefined".

function load3DObject(url, meshMaterial) {
  let mesh;
  let url3DObject = url;
  let Object3dMaterial = meshMaterial;

  loader.load(
    url3DObject,
    function(gltf) {
      let ArrowModel = gltf.scene;

      mesh = new THREE.Mesh(ArrowModel, Object3dMaterial);

      mesh.castShadow = true; //default is false

      mesh.receiveShadow = false; //default

      scene.add(mesh);

      scene.updateMatrixWorld(true);

      Objects.push(mesh);
    },
    undefined,

    function(error) {
      console.error(error);
    }
  );

  console.log(mesh);

  return mesh;
}

Answer №1

The asynchronous nature of the loader is the reason for this behavior. The load function is called, which in turn invokes a callback function upon completion. However, the mesh is returned immediately before the callback has had a chance to execute any tasks. Finding a proper solution may be challenging, but seeking advice from seasoned JavaScript developers could provide valuable insights.

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

Exploring Typescript: Understanding the nuances of importing and exporting values or references

Currently, I am facing a challenge while converting Javascript code to Typescript, specifically with regards to import and export functionality: Intended Functionality: I aim to import 'POST_Requirements' into multiple other files. Each file tha ...

The es6 object class is not defined

Hey there, I'm currently working on a simple pong game and encountering an issue with passing the player object into drawPlate. It seems to be printing the information correctly, but then I get hit with an Uncaught TypeError exception. The data print ...

Using C# Selenium WebDriver to interact with JavaScriptExecutor for handling prompt windows

I am faced with a JavaScript Prompt Window that I need to handle. Previously, I was able to manage a simple prompt with only an 'OK' and 'Cancel' button using the following code: ((IJavaScriptExecutor)ts.getDriver()).ExecuteScript("win ...

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...

Creating fixed values in HTML

I need to maintain consistency in the headings of multiple tables spread across 3 HTML pages. The heading structure is as follows: <thead> <tr> <th>MyHeading</th> </tr> </thead> My goal is to store the string MyHeadin ...

Guide to assigning IDs to multiple paragraphs within a parent element using a for loop

Is there a way to use a for loop to set ID for each <p> inside a <div> element? HTML <div id="article"> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

Troubleshooting Initialization Problem in Three.js Version r71

I encountered an issue: TypeError: undefined is not an object (evaluating 'data.initialized') Any tips on resolving this? I am currently working with three.js (r71), which has addressed the #5831 bug. ...

How can I trigger a masterpage function from a contentpage in asp.net?

I am trying to call a function on the masterpage from a content page in the codebehind. Here is my attempt: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert__", string.Format("setStatusBarMessage('{0}',{1});", barMessage, ty ...

The positioning of the "add" and "remove" buttons is incorrect in django-dynamic-formset

Yesterday, my app was functioning perfectly. However, after making some changes to the .css properties in the browser, I noticed that the django-dynamic-formset script is now malfunctioning. The "Add" and "Remove" buttons are appearing for each input in th ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

Is it possible to utilize a variable as a column name in MySQL when working with Express?

At the moment, I am encountering an issue where the table name is surrounded by quotation marks as it is a string. This causes the server to crash. const update = 'the name of my column'; const UpdateQuery = `UPDATE scores SET ${mysql.escap ...

If I use jQuery's ajax method to send a CSV file to my Node.js + Express server, where would the file be stored on the server?

I need help with sending a CSV file from my client to my Node.js and Express server using jQuery's ajax POST method. Once the CSV file reaches the server, I am unsure of how to access it. My objective is to pass the CSV file into my route's middl ...

Uploading information to a server using Angular.js

I am currently working on developing an application with the following code snippet: function attendeeCtrl($scope, $http) { $scope.submit = function () { console.log($scope.noattendees); $http({ method: 'POST', ...

Is it possible to utilize AJAX requests within Web Workers?

Ensuring that the latest changes made by the user on my web application are saved to the database is crucial. To achieve this, I have a function that sends the data to the database when the user closes the page: window.onbeforeunload = sendData; However, ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Scrolling Effect with Fixed Background Image in FullPage JS

I am trying to use FullPage JS to create a fixed video background with scrolling content. The issue I am facing is that when I set the video to section 1, it shifts to a white background when scrolling. Any assistance would be highly appreciated! #fullp ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...