Reputation: 21
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.
Upvotes: 0
Views: 2333
Reputation: 730
Javascript will not wait for the return value of an asynchronous function. Assume that someFunction and someAsyncFunction both return the value 'x'.
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'.
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.
Upvotes: 1