Waiting for XHR to complete before dealing with asynchronous problem in OBJLoader

In need of assistance on how to make OBJLoader solely return the object without adding it to the scene. I am encountering a synchronization issue where my code does not properly wait for the XHR request, resulting in errors.

Check out the example below:

var loader = new THREE.OBJLoader();

// create a mesh from an obj file   
function createObject( objFile, objName ) {
    object3d = loader.load( objFile , function ( object ) {
        object.name = objName;            
        console.log(object);
        return object;
    })
    return object3d;
}

car = createObject('path/to/car.obj', 'abc123');
car.position.y = 10;

The console output looks like this:

1. Uncaught TypeError: Cannot set property 'position' of undefined test.html:171
2. XHR finished loading: GET "path/to/car.obj". Three.js:11377
3. THREE.Object3D {id: 7, uuid: "9E8DC838-E68B-4FCA-A6AD-863D5D06D31F", name: "abc123", parent: undefined, children: Array[1]…}

Error (1) occurs because 'car.position.x' is executed while the XHR request is still ongoing and the object is null. My code lacks the necessary waiting time. However, (2) and (3) indicate that the load request does eventually succeed.

Any thoughts on resolving this issue? How can I modify createObject() so that it waits for the XHR request to complete before proceeding? Or is there a better way to structure this process?

Answer №1

To efficiently load an object in your method, create a designated "container" and then insert the loaded object into that container.

var loader = new THREE.OBJLoader();

// Function to create and return a mesh from an obj file   
function generateObject( objFile, objName ) {
    var container = new THREE.Object3D();
    loader.load( objFile , function ( object ) {
        object.name = objName;
        container.add( object );
    })
    return container;
}

car = generateObject('path/to/car.obj', 'abc123');
car.position.y = 10;

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

Activate a spinner when a button is clicked within a row of an antd table

I created a table with a column that includes a button like the one below: const columns = [ ... { title: "button", dataIndex: "key", render: (text, record) => { return ( <Button icon={<Del ...

Interacting between React and Express with CKEditor 5: How to send a request

import React, { Component, useState, useEffect } from 'react'; import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import axios from 'axios'; import pa ...

Delete the click event listener that was previously assigned by a different script

After extensive investigation using the Chrome developer tools, I have identified a click event listener that needs to be removed: https://i.sstatic.net/dnB3Q.png I successfully removed the listener using the developer tools. Further analysis revealed th ...

I am unable to transfer information retrieved from the fetch call to the express API

I'm facing a puzzling issue that has me stumped - I have code that should be working, but it's not. const getPhones = async () => { await fetch(url, requestOptions) .then((response) => response.text()) .then((XMLdata) => { ...

md-input container displays content only upon user interaction

Currently, I am working with AngularJs 1 and Angular-Material Design. One issue I encountered was with a md-input container used for file uploading. The problem I faced was that even after selecting a file, it wasn't being displayed in the md-input co ...

Update the HTML table by changing the first cell in the first row to span multiple

I currently have a table structured like this: <table> <thead> <tr> <th></th> <th>Col1</th> <th>Col2</th> <th>Col3</th> <th>Col4& ...

What is the best PHP approach to back up frontend AJAX requests?

I am looking to improve the structure of my PHP website that utilizes AJAX calls on the front end. Right now, my AJAX calls a PHP page that contains all of my backend code, determining which PHP methods to run based on the parameters passed from the AJAX c ...

Angular7 is throwing an error saying it cannot read the property 'post' of undefined

Looking to create a custom validation in Angular 7. Here is the code snippet: CheckUserNameExisit(control: AbstractControl): { [key: string]: any } { console.log('in functions') return new Promise(resolve => { let httpClient: HttpClient ...

Could you please direct me to the section in the ECMAScript documentation that specifies the behavior of a resolved promise with its [[Promise

My objective is to compare the behavior of a promise's resolve function with the corresponding process outlined in the ECMAScript specification. Specifically, I am interested in understanding how the resolve function behaves when called with an object ...

Exploring Vue Component Features through Conditional Display

I am working with a vue component called <PlanView/>. In my code, I am rendering this component conditionally: <div v-if="show_plan" id="mainplan"> <PlanView/> </div> <div class="icon" v-else> ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

Choosing a MongoDB field that has been received from a data context

My application creates a table by iterating through the events using #each events. Each row in the table represents an event and contains 4 event tickets. When a user clicks on a ticket, a function is executed. For example, when the first ticket is clicke ...

JavaScript code altered link to redirect to previous link

I added a date field to my HTML form. <input type="date" name="match_date" id="matchDate" onchange="filterMatchByDate(event)" min="2021-01-01" max="2021-12-31"> There is also an anchor tag ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Problems with select box rendering in Internet Explorer with Materialize CSS

When using materializecss select box in Internet Explorer 9 or higher, scrolling with the mouse button is not working. You must click on the scroll bar inside the select box for it to scroll. This issue does not occur in other browsers. I have attached a s ...

Implementing relationships in microservices with Prisma and NestJS

Schema for User Management service: model User { id String @id @default(uuid()) username String @unique email String @unique password String } Schema for File Management service: model File ...

Child class component unable to access React context value

Having some trouble with accessing a React context value in Employee.js that was set in App.js. It's not rendering correctly and I'm new to React. Any help would be appreciated. Thank you in advance. //index.js export const employeeContext = Rea ...

Function that is triggered by scrollbar height indicator

I'm currently utilizing jQuery to retrieve the user's current height and triggering an animation function once they reach that height (similar to reactive websites where animations occur as the user scrolls down the page). However, I am struggli ...

Invoking a PHP script within a div by clicking a button with the help of AJAX requests

I am currently utilizing an ajax script to call a php page named "MAINPAGE.PHP" by clicking on a button. This page contains an echo statement within a div with the id "YOURDIV". However, it seems that it's not properly calling the "MAINPAGE.PHP". Belo ...

Issue with codeigniter and jquery login functionality not triggering/responding

My controller had a working login function that suddenly stopped functioning after some changes were made. The login feature consists of two input fields for username and password, along with a submit button. //Javascript function initLogin(e) { e.p ...