Retrieve the Three.js object from an array

As part of a course requirement, I am tasked with creating a simple game using Three.js. One of the tasks involves setting up an array of spotlights in the following manner:

function loadLights(roomWidth, roomHeight) {
    let spotlights = [];
    fetch(configLights).then(res => res.text()).then(data => {
        const doc = yaml.load(data);
        const ambient = new THREE.AmbientLight(doc.ambientLight.color);
        ambient.intensity = doc.ambientLight.intensity;
        scene.add(ambient);
        let isAmbient = true;
        for (const r in doc) {
            const room = doc[r];
            if (isAmbient) {
                isAmbient = false;
                continue;
            }
            for (const spot in room) {
                for (let i = 0; i < 5; i++) {
                    const obj = room[spot];
                    let sl = new THREE.SpotLight();
                    sl.intensity = obj.intensity;
                    sl.decay = obj.decay;
                    sl.distance = obj.distance;
                    sl.penumbra = obj.penumbra;
                    sl.castShadow = true;
                    sl.shadow.mapSize.width = 1024;
                    sl.shadow.mapSize.height = 1024;
                    sl.receiveShadow = true;
                    scene.add(sl);
                    spotlights.push(sl);
                }
            }
        }
    });
    //START
    console.log(spotlights);
    return spotlights;
}
I am working with Parcel which requires me to utilize fetch to retrieve and open a yaml-file. The contents of the yaml-file are structured as follows:

ambientLight:
  color: "0x404040"
  intensity: 0.3
room:
  spotRoom:
    intensity: 1.4
    decay: 10
    penumbra: 0.5
    distance: 100

Upon printing the array "spotlights" in the console, the output looks like this: https://i.sstatic.net/154AF.png

I'm having trouble accessing these objects. Attempting spotlights[0] returns undefined.

Answer №1

The issue lies with the utilization of the fetch() function, which is asynchronous, causing you to prematurely log the result before the spotlight data is fully loaded. To resolve this, ensure you wait for the fetch operation to finish by implementing another async function:

async function displaySpotlights() {
    const spotlightsData = await loadLights(roomWidth, roomHeight);
    console.log(spotlightsData);
}
displaySpotlights();

Note: Utilizing .then within the loadLights function without wrapping the console.log isn't sufficient to maximize the benefits of using a promise.

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

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

What steps should I follow to ensure my slider keeps looping?

I have created a slider using a ul list that contains 15 li elements. The slider displays groups of 5 elements at a time. However, after clicking the next or previous buttons three times, it stops displaying any new elements. This is because I used right: ...

When the user clicks, reveal the form with a seamless transition

Check out my jsfiddle here: http://jsfiddle.net/tz52u/9/ I'm curious about how to create a smooth transition for the 'on click' event, so that it gradually appears on the page instead of appearing instantly? Any assistance would be greatl ...

What is the best way to resize an image to fit its surroundings within a nested box?

Have you ever heard of a website called SPAM? It has a unique homepage that I want to replicate using JavaScript, jQuery, and some CSS. My main challenge is figuring out how to adjust the image size to match the center box on the page. I want to create th ...

Using Angular to sort arrays based on the values in a separate array

I have a unique setup where there is a table containing select options in each row. The value of the select option changes based on the 'dataType' specified for that particular row. Here is an example of my Table Array: { 'name':' ...

Determine the number of entries in a JSON object

I am encountering an issue while trying to calculate the number of records in a JSON object, as I am getting an incorrect count. Snippet var jsonObject = {"d":"[{\"Country\":\"\",\"CountryCo ...

Exploring the properties of a file directory

As I try to access the d attribute of a path that was generated using Javascript, the output of printing the path element appears as follows: path class=​"coastline" d="M641.2565741281438,207.45837080935186L640.7046722156485,207.0278378856494L640.698 ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

The functionality of Angular binding seems to be experiencing some issues

Just starting out with angular and trying to figure things out. I've made an HTML page where the user can input text into a textbox, and whatever is entered should simultaneously appear on the screen. Here is the HTML code snippet: <html ng-app&g ...

Double Ajax calls being made in Laravel application

I am working on a Laravel application for managing tasks. The application has a form with four fields: one for the CSRF token, two hidden fields for IDs, and an input field to capture the task title. For submitting the form, I have implemented AJAX. Howev ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

Version 5.3 of Laravel combined with Vue 2

Working with Vue 2 in a fresh Laravel 5.3 project, I'm faced with a challenge regarding binding a URL in the Laravel format. I've extracted some configuration rows from a database and my goal is to iterate over them to display the data, followed ...

Guide to linking multiple images to a single Post instance

Is it possible to attach each array of images to their post using the foreign key placePlaceId? For example, in the first object with place_id:3, I want to attach all the images with the foreign key placePlaceId:3. This is my approach to achieving this go ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Tips for resolving the [vue/no-use-v-if-with-v-for] warning in Vue

I am encountering an issue with a div element that supports v-for and v-if. The output is correct, however, there is a warning that I find quite annoying: [vue/no-use-v-if-with-v-for] The 'prit_type_ids' variable inside the 'v-for' dir ...

Encountering challenges with CORS implementation in a test application

I am struggling with an issue while trying to send a request to a website for ping. I have tried using jsonp, but it's not working as expected. I attempted to implement cors, but I keep getting the error message "No 'Access-Control-Allow-Origin&a ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...