Problem with Javascript Method Return

1
const data_ = () => {
    let array = []
    fs.createReadStream('./files/treinamento.csv')
        .pipe(csv())
        .on('data', (data) => {
            array.push(data)
        })
        .on('end', () => {
            console.log(array)
        })
}

Using console.log I get return with the values I want, but replacing the console with return the function returns me an empty array. Could someone give me a solution?

    
asked by anonymous 20.05.2017 / 21:51

1 answer

2

Can not return of this function because it is asynchronous. What you have to do is chain functions.

That is, if you have a function that needs this result, you have to call it by passing it the data you need within that end . Something like this:

function usarData(arr) {
  // esta função será chamada quando a array estiver pronta.
  console.log(arr);
}

const data_ = (fn) => {
  let array = []
  fs.createReadStream('./files/treinamento.csv')
    .pipe(csv())
    .on('data', (data) => {
      array.push(data)
    })
    .on('end', () => {
      fn(array)
    })
}

data_(usarData);
    
21.05.2017 / 09:22