Loading Textures in Three.js Using async / await is the Way to Go

Recently, I took a Drawing class and learned about creating objects:

export class Drawing {
    constructor(texture) {        
        const material = new MeshBasicMaterial({
            color: 0xffffff,
            map: texture
        });
        this.mesh = new Mesh(new PlaneGeometry(texture.image.naturalWidth / 20, texture.image.naturalHeight / 20), material);
    }

    setPosition(x, y, z) {
        this.mesh.position.x = x;
        this.mesh.position.y = y;
        this.mesh.position.z = z;
    }
}

I wanted to access the texture.image properties to set up the PlaneGeometry correctly. To achieve this, I needed to perform some async/await calls before creating a Drawing object within the World constructor:


let world;
let raycasterDown;
let prevTime = performance.now();
const direction = new Vector3();
const globalInputs = new GlobalInputs();
const textureLoader = new TextureLoader();

const promiseTextureBack = (pathName) => {
    return new Promise((resolve) => {
        resolve(textureLoader.load(pathName));
    });
}

const allTexturesPromises = [];
drawingPaths.map(pathName => {          //drawingPaths is an array of string
    allTexturesPromises.push(promiseTextureBack(pathName));
});

const loadingWorld = async () => {
    const allTextures = await Promise.all(allTexturesPromises); 
    console.log(allTextures[0]);
    world = new World(allTextures);
    document.body.appendChild(world.renderer.domElement);
    world.instructions.addEventListener('click', function () {
        world.controls.lock();
    });
    world.controls.addEventListener('lock', function () {
        world.instructions.style.display = 'none';
        world.blocker.style.display = 'none';
    });

    world.controls.addEventListener('unlock', function () {
        world.blocker.style.display = 'block';
        world.instructions.style.display = '';
    });
}

init();

function init() {
    loadingWorld();
    raycasterDown = new Raycaster(new Vector3(), new Vector3(0, -1, 0), 0, 10);
    document.addEventListener('keydown', (event) => {
        globalInputs.onKeyDown(event);
    });

    document.addEventListener('keyup', (event) => {
        globalInputs.onKeyUp(event);
    });
    window.addEventListener('resize', onWindowResize);
    animate();
}

However, when I checked the console using:

    console.log(allTextures[0]) 

I got this link instead:

https://i.sstatic.net/mi2a2.png

The image still remained undefined. After investigating further, it seems like the issue lies within:

textureLoader.load(pathName)

If you have any suggestions or solutions, feel free to share!

Answer №1

When utilizing the load method, it requires a callback function and does not support returning a value for the `resolve` method. Rather than implementing the complex `promiseTextureBack` code, consider using the loadAsync method which simplifies the process by providing a promise:

const allTexturesPromises = drawingPaths.map(pathName => {  
    return textureLoader.load(pathName);
});

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 there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

Discovering the function invoker when in strict mode

I am facing a challenge in my Angular controller where I have a function called getGames() that can be triggered by both the init() and update() functions. The issue is, I need to handle these two scenarios differently based on which function called getGam ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

Encountering the "Invalid Element Type" error in a Vue Native project right after setting it up

After creating a vue-native project with the command vue-native init henry-pager, I navigated to the directory and initiated the online builder by running expo start. However, when attempting to run it on the web platform, an error message appeared: Error: ...

Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example: var obj = {hello: [2]}; var obj2 = {hola: [4]}; _.extend(obj, obj2) obj2.hola = 5; conso ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

Creating distinct short identifiers across various servers

Utilizing the shortid package for creating unique room IDs has proven effective when used on a single server. However, concerns arise regarding the uniqueness of IDs generated when utilized across multiple servers. Is there a method to ensure unique ID g ...

JavaScript code for the submit button to proceed or halt the form submission

Within my JSP file, I have the following code snippet: <input type="submit" value="Transfer ULD" onclick="doSomething();" name="_eventId_transferULDTransition"/> The doSomething() function mentioned above is a JavaScript method. function doSomethi ...

Having trouble accessing the ng-model within ng-repeat in the controller of an AngularJS component

One approach I am considering is to use ng-model="model.ind[$index]" in order to keep track of the active tag. This way, when I click on a tag (specifically the 'a' tag), both the parentIndex and $index will be passed to my controller. Subsequent ...

Leveraging AJAX to send a form filled with dynamic content to multiple destinations

I have a hidden form that needs to be submitted to two different locations. The form is automatically filled using the .val method in jQuery. How can I write the ajax script to submit this form to two different locations? Is it possible to do this without ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Issue with redirect after submitting CakePHP form not functioning as expected

I am in the process of developing a button that will submit a form and then redirect to another page. $('#saveApp').click(function() { event.preventDefault(); $("form[id='CustomerSaveForm']").submit(); // using the nati ...

When attempting to insert the "$binary" key into MongoDB using Node.js, an error occurs stating that the key must not begin with a "$" symbol

When utilizing the node driver to insert records into mongo, I encountered an issue with a certain field in my collection: { "$binary": "base64 encoded binary" }. If I directly input a key beginning with $, it triggers an error: Error: key $binary must no ...

Check a field for validation only when it is visible on the screen

One challenge I'm facing is with an asp.net webform. I have a hidden field that is only displayed when a user selects a radio button. The catch is, this hidden field needs to be mandatory only when it's visible; otherwise, I don't want it to ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

Fixing the error: "React-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a valid function"

Every time I change the option in the selector, I keep encountering this error: "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function" :( import React from "react"; import Product from "./Product" ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

Using a Javascript loop to showcase values from a database

As a Python developer who is new to JavaScript and AJAX, I am currently working on creating a pie chart that displays database values. $(document).ready(function () { google.charts.load('current', { 'packages': ['corechart&ap ...