0

I prepared a function that reads a json file and I want to return an array that I can then use to create charts.

The function reads the file correctly and generates the array as intended within the fetch() function, but I am not able to pass it further. What I am doing wrong?

function getOrderDays(file, col){

const myRequest = new Request(file);

fetch(myRequest)
.then(response => response.json())
.then(data => {

    var selecteddata = [];
    
    data.forEach(function(item) {
        selecteddata.push(parseInt(item[col]));
    })
    
    // Create an array containing the indexes of values > 0 :
    var indexes = [0]; // I need a 0 at the beginning
    var i = 0;
    while (data[i]) {
        if (selecteddata[i] != 0) {
            indexes.push(i)
        }
        i++;
    }
    console.log(indexes); // This produces the result as needed       



}).catch(err => console.error(err));

return indexes; // This is returning an empty array
}
Nicola Ibba
  • 77
  • 1
  • 8
  • 3
    *"What I am doing wrong?"* The `return` statement of `getOrderDays` will execute before any of the `then` callbacks is executed. `getOrderDays` has to return a promise. – Felix Kling Jan 09 '21 at 13:19
  • 1
    This might also help to learn how to think about callbacks: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Jan 09 '21 at 13:20
  • I did already try to place return after the console.log(indexes); // This produces the result as needed line but I get the same (empty) result – Nicola Ibba Jan 09 '21 at 13:35
  • You have to return the promise return by `then`: `return fetch(...).then(...).then(data => { ... return indexes; });`. – Felix Kling Jan 09 '21 at 14:33

0 Answers0