FileLoader: getting data ouf of the onLoad function?

Hey,
i’m currently trying to use the FileLoader to load an external XML file, but i have a hard time to grasp how to get usable data from it.

As in the documentation i can show the data of the file in the console, but i cannot return it. I tried to assign it to a variable outside of the onLoad-function but it didn’t worked. May it an idea to make it async?

My code (the file is delivered by another module and the function should return the data):

// load xml file
import { FileLoader } from '../../../../vendor/three/build/three.module.js';
import { Cache } from '../../../vendor/three/build/three.module.js';

Cache.enabled = true;

function loadFile ( file ) {
	const loader = new FileLoader();

	const something = loader.load(

		file,

		//onLoad callback
		function ( data ) {
			console.log(data);
			},
	)

	return something ;
}

export { loadFile };

Thanks!

loader.load is an asynchronous function. That is why you need to provide an onLoad callback. If you want to work with asynchronous functions in a synchronous way (syntax wise, they still async of course) you can use Promises with async/await.

Have look at this example:

import * as THREE from 'three';

function loadFile(filePath) {
    return new Promise((resolve) => {
        const loader = new THREE.FileLoader();

        loader.load(filePath, (data) => {
            resolve(data);
        });
    });
}

async function test() {
    const data = await loadFile('example.txt');
    console.log(data);
}

void test();
1 Like