From the release of three.js R125 onwards, the recommended approach for achieving this task is by using the loadAsync method, which is now integrated into three.js:
This method now returns a promise. You can then utilize a 'then' function to retrieve the geometry of the STL file and create the mesh. While you could also opt for a traditional callback or an async/await structure, the example provided below utilizing the native three.js method presents the simplest solution. The example demonstrates how you can assign the geometry to a global variable once the promise is fulfilled and the STL file is successfully loaded:
// Global variables for bounding boxes
let bbox;
const loader = new STLLoader();
const promise = loader.loadAsync('model1.stl');
promise.then(function ( geometry ) {
const material = new THREE.MeshPhongMaterial();
const mesh = new THREE.Mesh( geometry, material );
mesh.geometry.computeBoundingBox();
bbox = mesh.geometry.boundingBox;
scene.add( mesh );
buildScene();
console.log('STL file loaded!');
}).catch(handleFailure);
function handleFailure(){
console.log('Failed to load the STL file!');
}
function buildScene() {
console.log('STL file has been loaded, proceeding to build the scene');
// The bounding box of the STL mesh is now accessible
console.log(bbox);
// Continue building your scene...
}