-1

So I am a beginner in learning Node and trying to understand the asynchronous part of it. The following code in readIn should wait for readFile to finish and then execute whenDone to update the arr variable, but whatever value I pass in as it always shows that the arr is empty. I don't think the arr was ever mutated or the function whenDone never waited for the readFile to finish.

Can someone please explain what I'm doing wrong or misunderstood?

Thank you

var fs = require('fs');
var arr = [];

function readIn(callback){
    fs.readFile(process.argv[2],'utf8',function whenDone(err, fileContent){

        arr = fileContent.split('\n');
        callback();
    })
}

var result = arr.length -1

function printOut(){
    console.log(result);
}

readIn(printOut);
UWGOOSE
  • 833
  • 3
  • 11
  • 20
  • You define the arr, then the function readIn. Then you define a var result which gets equal to -1 because the length is 0 at the time. Then you define the print function and call the readIn function which will print -1. – Giannis Mp Feb 25 '18 at 20:03
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Wiktor Zychla Feb 25 '18 at 20:06

1 Answers1

0

The readFile function is asynchronous so it returns control to the caller. You should rewrite like this:

var fs = require('fs');


function readIn(callback){
    fs.readFile(process.argv[2],'utf8',function whenDone(err, fileContent){
        var arr = fileContent.split('\n');
        callback(arr);
    })
}


function printOut(arr){
    console.log(arr);
}

readIn(printOut);
ema
  • 5,668
  • 1
  • 25
  • 31