Problem with Javascript Method Return

Asked

Viewed 46 times

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. Someone could give me a solution ?

1 answer

2


It is not possible to do return of that function because it is asynchronous. What you have to do is chain functions.

I mean, if you have a function that needs that result, you have to call it, pass the data you need inside that end. Something like that:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.