Ways to reach a variable beyond a subfunction in javascript

Below is a function I have created that utilizes a GLTF loader to import a model into the scene from another class:

    LoadModel(path){
        this.gltfLoader.load(
            path,
            (gltf) =>
            {
                this.scene.add(gltf.scene)
            }
        )
    }

I am trying to call this function from another class in order to add the returned gltf.scene mesh to the players array, which is intended to keep track of the players' meshes:

this.players.push(this.loader.LoadModel('./../static/player.glb'))

However, I am facing an issue where I cannot access the variable outside of the gltfLoader.load() function. This is demonstrated in the code snippet below:

LoadModel(path){
     let mesh = null
        this.gltfLoader.load(
            path,
            (gltf) =>
            {
                this.scene.add(gltf.scene)
                mesh=gltf.scene
                console.log(mesh) // prints gltf.scene
            }
        )
      console.log(mesh) //prints "null"
    }

Answer №1

To ensure smooth execution when this.gltfLoader.load is asynchronous and lacks a promise-based version, you can create a promise to handle the callback-style function.

// create a promise that resolves the result of gltfLoader.load, or "gltf"
async function loadMesh(path) {
  return new Promise(resolve => {
    this.gltfLoader.load(path, resolve);
  });
}

// insert this code where loadMesh is imported and players is within scope...
async createMesh() {
  let gltf = await loadMesh('some/path');
  let mesh=gltf.scene;
  this.experience.scene.add(mesh);
  this.players.push(mesh);
}

Answer №2

Upon logging out of the loader, the loading process is completed. You can achieve this by implementing the following approach:

function loadMesh(path, callback){
     let mesh = null
        this.gltfLoader.load(
            path,
            (gltf) =>
            {
                this.experience.scene.add(gltf.scene)
                mesh=gltf.scene
                callback(mesh)
            }
        )
    }

loadMesh('./../static/player.glb', console.log) // Success!

Adding to an array:

this.experience.loaderGltf.loadMesh('./../static/player.glb', (mesh) => this.players.push(mesh))

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

Is it possible for search engines to crawl and index specific pages within a web application that is powered by

I have created a web application with a dynamic JavaScript interface that communicates with the server through AJAX requests. The content of the page is determined by the data after the hashtag in the URL, which is fetched from the server and displayed acc ...

Downloading Several Files Simultaneously in Chrome

Since the last Chrome update, my website has encountered an issue. The code snippet below, which was designed to download multiple files, is now only opening the last file in the same tab. I have ensured that my Chrome settings still allow for multiple dow ...

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

Displaying URLs stylishly with Pills Bootstrap

When a pill is selected from the list, I need to display a specific URL that can be used elsewhere. However, there is an href="#pills-something" attribute that directs to an ID below. I am looking for something like: mysite.com/myspecificpill or ...

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...

The resizing of iframes in Javascript is malfunctioning when it comes to cross-domain functionality

I have implemented a script to dynamically resize iframe height and width based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newheight=docume ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Drop delete method not functioning as expected

Currently, I am trying to work on a JavaScript delete function that is supposed to delete a row from an SQL table. However, it seems like the function is not working properly. Let me share the code with you: $(document).ready(function(){ $( "#draggabl ...

How do I convert the object value/data to lowercase in JavaScript using underscore for an HTML5 document?

I am working with an array of objects (arr) where each object consists of 3 properties (Department, Categories, ProductTypes). The values for these properties are a mix of upper and lower case. To perform a comparison between arr and a search filter (alrea ...

What is the best method for implementing numeric input in Vue.js?

I have experience developing web apps using Nuxt.js. I am currently trying to implement validation that excludes negative values and decimal points in all input tags (around 20-30) within the same Vue component. My approach involves injecting validation ru ...

Boosting your website with a slick Bootstrap 4 responsive menu that easily accommodates additional

I have incorporated a main menu in my website using the Bootstrap 4 navbar. However, I also have an additional div (.social-navbar) containing some extra menu items that I want to RELOCATE and INSERT into the Bootstrap menu only on mobile devices. Essentia ...

Pair of elements connecting in Vuejs

What is the best way to efficiently organize data and communication between two Vue.js components? Here's an example scenario: 1) I have a component item(v-for="item in items) a {{item.name}} 2) And then the second component card(v-for="item in it ...

Issue with intersection not occurring in InstancedBufferGeometry

After experimenting with the InstancedBufferGeometry, I found that it's highly effective. However, I noticed that intersections aren't working as expected with InstancedBufferGeometry. Upon inspection of the threejs(r85) library, I discovered tha ...

Is there a way for me to view the specifics by hovering over a particular box?

Whenever I hover over a specific box, detailed information appears, and when I move the mouse away, the details disappear. HTML <nav> <div> <div class="nav-container"> <a href="./about.html" ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...

How to effectively create factories in AngularJS

I stumbled upon this angularjs styleguide that I want to follow: https://github.com/johnpapa/angular-styleguide#factories Now, I'm trying to write my code in a similar way. Here is my current factory implementation: .factory('Noty',functi ...

Define the position of a scrolled area within an HTML document to create a

In my current project, I have a scrollable area that highlights the selected div in gray. The HTML is written using Ember (hbs) and includes code to handle this functionality. Below is an example of how the div looks: https://i.sstatic.net/T2Lur.png Here ...