Problems with variable scoping of an ImportMesh method

I have a sample code here:

function foo() {
var useMesh; // ( line1)
BABYLON.SceneLoader.ImportMesh('mesh_name', './', 'mesh.babylon', scene, (meshes, particles, skeletons, animations) => {
useMesh = meshes[0]; // (line 2)
useMesh.position.x = 10; // (line 3)
//and so forth (line 4)

How can I use the imported mesh as part of the outer scope? The scoping and callback order are lines 1, 3, 4 then 2. I want to use line 2 to execute before line 3 and after are called. What can I use accomplish that?

The reason I am doing that is that I am using imported mesh mixed with programmed meshes (such as BABYLON.MeshBuilder.CreateBox()) in the same function and they will interact together. And, there are multiple ImportMesh that are going to interact with each other in the foo function.

I know this is more of a JavaScript question than a BabylonJS question but it’s puzzling me. I tried to looked it up on StackExchange and Google trying to find hints on how to hoist the scope of the imported with general JavaScript queries but with actual answer. ImportMeshAsync does not work either or maybe I’m not using that right.

Any advice or hints, such as to any tutorials that can lead to my answer?

In your case, there are 2 patterns:

  1. Use the ImportMeshAsync function and simply await it so you do not have async issues
  2. you can only use the values in the onload callback (or at least after it triggered)

Thanks for the suggestion. I modified the code to this and a working solution was found.

async function foo() {
var useMesh = (await (BABYLON.SceneLoader.ImportMeshAsync('mesh_name', './', 'mesh.babylon')).meshes[0];
useMesh.position.x = 10;

I can’t believe it was that simple.

Thank you.