1

I've been spending way too much time on this issue... So i want to declare a 2D array called "positions" that can be used in other functions. using a parsing code that worked in the function "init", i tried to create a simple function called "parsing" as to avoid repeating the long parsing process every time i want to use the positions array. except when i console.log(positions) in other functions, it always returns an empty array = []. How come "positions" doesn't get modified in the parsing function and how do i do it? This is the code used:

var positions = [];

parsing();
init();

function parsing() {
    fetch('Petit_film_256_atomes.txt').then(response => response.text()).then(text => {
        const arr = text.split('\n')
            .map(line => line.trim())
            .map((arr) => arr.split(' '))
            .map(([size, x, y, z]) => ({ 
                  size: Number(size), 
                  x: Number(x), 
                  y: Number(y), 
                  z: Number(z) 
            }));
            while (arr.length > 0) {
                positions.push(arr.splice(0, size).slice(2));
            }
    })
}
Yujia Ding
  • 65
  • 5

1 Answers1

-1

I haven't looked closely at what's happening during all the .map calls, but the trouble is probably that parsing is not finished by the time init is invoked. You can try it this way:

var positions = [];

parsing(init);

function parsing(cb) {
    fetch('Petit_film_256_atomes.txt').then(response => response.text()).then(text => {
        const arr = text.split('\n')
            .map(line => line.trim())
            .map((arr) => arr.split(' '))
            .map(([size, x, y, z]) => ({ 
                size: Number(size), 
                x: Number(x), 
                y: Number(y), 
                z: Number(z) 
        }));
        while (arr.length > 0) {
            positions.push(arr.splice(0, size).slice(2));
        }
        if (typeof(cb) === 'function') {
            cb();
        }
   })
}
arbuthnott
  • 3,819
  • 2
  • 8
  • 21
  • Don't take a callback. Use the promise that you have, and return it! `parsing().then(init)` – Bergi Aug 23 '17 at 18:16