The Javascript array contains information, but its length is currently empty

UPDATE: It seems that I misunderstood how promises work, leading to a synchronization issue. I mistakenly assumed that ".then" waits for the promise to resolve, which is not the case.

An unusual error has cropped up that has me stumped.

I'm puzzled by this code which generates the following results in the Chrome console.

Despite the array containing data and having a length, when I try to access the length property, it shows as zero. (I'm also unable to iterate over it using map)

Your insights and assistance in unraveling this mystery would be greatly appreciated.

const readFile = (file) => (
  new Promise((resolve) => {
    const fr = new FileReader();
    fr.onload = () => {
      resolve(fr.result);
    };
    fr.readAsText(file);
  })
);

const readFiles = (files) => {
  const readFiles = [];
  files.forEach((file) => (readFile(file)).then((data) => readFiles.push({name: file.name, data })));
  return readFiles;
};

const scenes = readFiles(...grabbed from file picker dialog...)
console.log('scenes: ', ui.value.scenes);
console.log('length: ', ui.value.scenes.length);

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

Answer №1

To retrieve the data from a read file, you must handle it as a promise and access the resolved value within the then method as shown below:

 readFile().then( (scenes) => {
     console.table(scenes)
 }

When using console.log in Chrome and Firefox, the output is a live version of the object that can be modified by later code due to promise resolution. If you want to display the state of the object at a specific time, you should use console.log(JSON.stringify(obj)) Here is an excerpt from MDN

It's important to note that logging objects in the latest versions of Chrome and Firefox will provide a reference to the object, not necessarily its 'value' at the moment console.log() is called. The value displayed reflects the object at the time you inspect it.

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

The swf file doesn't stretch to fit the window when the height is set to 100%

Struggling with creating a flash recorder controlled by JavaScript? Trying to get the flash to fill the browser window but disappearing when setting height or width to 100%? Where am I going wrong? <div id="flashrecorder"> <object wmode="trans ...

Obtain values from a specific set, and then filter out values from an array that correspond to the index of that set into distinct arrays

The Problem I'm Facing Currently, I am dealing with a large data table that contains a mix of relevant and irrelevant data. My goal is to filter out the information I care about and display it in a more concise table. Using RegEx, I have managed to i ...

How can I export an array in Ajax/PHP to the user as a .txt file?

Currently, I am working on a PHP file named "php-1" that is responsible for generating an HTML page. This particular file requests input from the user and once the user clicks on a button labelled "getIDs" (it's worth noting that there are multiple b ...

Utilize Function to Gain Access to React Context

As I work on developing a package that enhances the responsiveness of my React widget, I have encountered an issue. The responsiveness now relies not on the viewport width, but rather on the width of the widget container element. Presently, I am wrapping ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: https://i.sstatic.net/M0G1W.png Take a look at my file structure: https://i.sstatic.net/nVsUX.png I considered usi ...

Invoke a function from a different source in JavaScript

Below is the JS function implemented: function addMemberToLessonDirect(id) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ...

Adding a Key-Value pair to JSON using Python

I need to update a JSON file by adding new key value pairs to the existing data structure. I have figured out how to add to the parent level, but I am stuck on how to add values to the child items. JSON file: { "students": [ { "name": "Hendri ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

Tips for resolving the issue: React is unable to recognize the X prop on a DOM element

I have been experimenting with a library known as react-firebase-js for managing firebase authentication. However, my grasp of react and the concept of provider-consumer is somewhat limited. Initially, I created a large JSX construct at the top level, whi ...

Upon clicking, choose a specific todo ID

I'm currently in the process of developing a basic todo application, and I am receiving data through props from a GraphQL Server in the following format: id:"5b3447a7b9d0e02144538972" text:"biibbb" My current issue is that when I click on the checkb ...

Redux export does not complete correctly unless brackets are used

I'm trying to understand why the main JS file is having trouble importing todo from './actions' without brackets, while there are no issues with importing todos from './reducers'. Main js-file: import { createStore } from 'r ...

Utilize Javascript to interact with specific Objects

Working with Node.js, I have written a code that produces the following output: entries: [ { data: [Object] }, { data: [Object] }, { data: [Object] }, ... { data: [Object] } ] } null The code snippet is as follows: targetingIdea ...

In Vue.js, the properties of components are not defined

Currently, I am experiencing an issue where I am passing a props to one of my views, but when I print the result in console it shows up as undefined. This is causing difficulties as I am unable to make requests or consults. Here is the code snippet in ques ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

The function cannot be accessed during the unit test

I have just created a new project in VueJS and incorporated TypeScript into it. Below is my component along with some testing methods: <template> <div></div> </template> <script lang="ts"> import { Component, Vue } from ...

Express 4 Alert: Headers cannot be modified once they have been sent

I recently upgraded to version 4 of Express while setting up a basic chat system. However, I encountered an error message that says: info - socket.io started Express server listening on port 3000 GET / 304 790.443 ms - - Error: Can't set headers ...

What is the best way to convert items from a foreach loop into a JSON string using the json_encode() function in PHP?

I want to populate a string with all the emails fetched from the database, in order to use JavaScript for checking if the email entered by a user in a form field is already registered. I'm attempting to utilize the json_encode() function. $connec ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

What is the best way to manage elements within an array across two distinct view controllers?

Currently in the process of creating a quiz application, the initial UIViewController presents the user with a question and four answer buttons to select from. If the user answers correctly, the question is removed from the array of questions. However, upo ...

Transform JSON data into an Array to create visual representations on a graph

Retrieving values from a MySQL database and exporting them to JSON can be done with the code snippet below: <?php require_once 'includes/global.inc.php'; $query = "SELECT * FROM `chart_sales` ORDER BY id LIMIT 0 , 100"; $result = mysql_que ...