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.

3
  • Research asynchrony in JavaScript. JavaScript is unlike other languages in that it is not blocking - everything should happen asynchronously. Commented Aug 18, 2017 at 19:32
  • 2
    Possible duplicate of How do I return the response from an asynchronous call? Commented Aug 18, 2017 at 19:33
  • 2
    I'm not even sure if the code above is valid JS. Commented Aug 18, 2017 at 19:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.