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

9
  • 2
    it may be that ui.value.scenes is getting updated after the log statements Commented Apr 15, 2018 at 3:58
  • 1
    By any chance is scenes being populated asynchronously? Commented Apr 15, 2018 at 3:58
  • 1
    This is not enough to identify the problem. Please edit the question and include a minimal reproducible example. Commented Apr 15, 2018 at 3:58
  • 1
    Give us some more code plz Commented Apr 15, 2018 at 4:07
  • 1
    Have you read the little i icon next to []? Commented Apr 15, 2018 at 4:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.