0

I am reading a CSV file using a function in Java script and waiting for the return value, but the script is not performing the actions required. CSV Reader

`parseCSV : function(file) {
        return new Promise(function (resolve, reject) {
            var parser = csv({delimiter: ','},
                function (err, data) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(data);
                    }
                    parser.end();
                });
            fs.createReadStream(file).pipe(parser);
        });
    }`

Calling the CSV Reader

`csvreader.parseCSV(csvFile).then(function(data) {
        data.forEach(function(line) {
            console.log(line[0]);
            console.log(line[1]);
            });
        },function(reason){
            console.error(reason);
            });`

In the above code, it's not waiting for the return data.

Vambcool
  • 11
  • 3
  • Research asynchrony in JavaScript. JavaScript is unlike other languages in that it is not blocking - everything should happen asynchronously. – Stephen S Aug 18 '17 at 19:32
  • 2
    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) – Russley Shaw Aug 18 '17 at 19:33
  • 2
    I'm not even sure if the code above is valid JS. – Joseph Aug 18 '17 at 19:35

1 Answers1

1

Javascript will not wait for the return value of an asynchronous function. Assume that someFunction and someAsyncFunction both return the value 'x'.

Synchronous

var result = someFunction();
console.log(result);  // This line would not be executed until someFunction returns a value.  
                      // This means that the console will always print the value 'x'.

Asynchronous

var result = someAsyncFunction();
console.log(result); // This line would be executed immediately after someAsyncFunction 
                     // is called, likely before it can return a value.
                     // As a result, the console will print the null because result has
                     // not yet been returned by the async function.

In your code above, the callback will not be called immediately because parseCSV is an asynchronous method. As a result, the callback will only run once the asynchronous function completes.

Nick Painter
  • 720
  • 10
  • 13