Value of variable dont store in function

Hallo, I try to load model in gltf format. I use Blender to export my model, and use gltfLoader in three js project. Everythink works fine, except one thing - I cannot acces to my model outside of load() function. I want to save my model (or scene) to variable for further manipulation. But i have found, that everthing, what i save to variable in load function of gltf loader is lost after this function is executed.
I give example code:

var a;
init();
console.log(a) //this printed "undefined" instead of 5

function init(){
    const gltfLoader = new THREE.GLTFLoader();
    gltfLoader.load('objects/terrain.gltf', 
        function(gltf) {
            a=5;
    });
//If i put a=5; here, everithing works properly
}

I already tried to write “window.a=5”, but it doesn’t work too.
Exept this problem everythink works ok, so I can load my scene, and even manipulate with it in load() function, but i cannot store it to some variable for later manipulations (as variable “a” in my example").

This is not so much a Three.js question, but a Javascript question. You’re dealing with Javascript Asynchronicity, where the function inside .load() doesn’t get called until after the file gets loaded (this could take any amount of time), but you’re calling console.log() immediately after init(), so a=5 hasn’t happened yet!

The sequence of events goes like this:

  1. You declare var a;
  2. init() is invoked
  3. console.log(a) is executed
  4. After a few seconds, the function inside .load() is triggered, where you assign a=5

I recommend you read any tutorial that explains async Javascript behavior. Here’s one I found after a quick search:
https://www.pluralsight.com/guides/introduction-to-asynchronous-javascript

3 Likes

Thank you very much! :slight_smile: