Harsha Limaye
Harsha Limaye

Reputation: 1135

How to wait for createReadStream to finish?

I am confused because I cannot seem to extract a value from an asynchronous operation. Basically I have to parse a csv file and the operation is asynchronous as shown below.

const csv = require('csv-parser')
const fs = require('fs')
const results = [];
fs.createReadStream('courses.csv')
            .pipe(csv())
            .on('data', (data) => results.push(data))
            .on('end', () => {
                console.log(results);
            });

I am unable to completly extract and isolate the results variable from that stream. I have tried doing this by wrapping it with a promise but it shows pending. Here is what I am doing.

const getData = () => {
    const prom = new Promise((res, rej) => {
        fs.createReadStream('courses.csv')
            .pipe(csv())
            .on('data', (data) => results.push(data))
            .on('end', () => {
                res(results);
            });
    })
    return prom;
}

async function GIVEMEMYVALUE() {
    var result = await getData();
    return result;
};

let data = GIVEMEMYVALUE();
console.log(data);

I have read other questions relating to promises but I still don't see what I am doing wrong. I can do whatever I want with the results variable inside the 'end' callback but cannot seem to extract it(for whatever reason I want to extract it.)

  1. Is it wrong to want to extract that value outside the scope of the 'end' callback ?
  2. Can everything I possibly want to do with the results be done inside the callback ?

I have already gone through How do I return the response from an asynchronous call? but don't quite get it as it doesn't mention anything about pending promises.

Upvotes: 0

Views: 1221

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

GIVEMEMYVALUE returns also an promise. However you could shorten your processes alot:

const getData = () =>
  new Promise((res, rej) => {
    fs.createReadStream("courses.csv")
      .pipe(csv())
      .on("data", data => results.push(data))
      .on("end", () => {
        res(results);
      });
  });

getData().then(data => {
  console.log(data);
});

async/ await does not make your code work synchronous. As soon as you put async infront of your function, your function automatically returns an promise and acts like an promise.

Upvotes: 2

Related Questions