2

EDIT: this appears to be a sync issue due to me not understanding promises correctly. I assumed that the ".then" waited for the promise to resolve. This is apparently not the case.

I am encountering a strange error that I've never seen before.

I have this code which produces the following output in the Chrome console.

Clearly it is an array and it has data and a length, but when I print the length property it is zero. (I also can't iterate over it with map)

I'm really confused, any help would be much 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);

console

Garrett Fleischer
  • 177
  • 1
  • 3
  • 13

1 Answers1

3

What you return from read file is a promise so you should read the resolved value inside then method like this

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

The reason you could see values in console is because when using console.log in Chrome and Firefox it is a live version of the object that might be changed from later code (from promise resolve).
If you want to print state of object in time you can run console.log(JSON.stringify(obj)) Here is a snippet from MDN

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.

Moti Korets
  • 3,738
  • 2
  • 26
  • 35