I am clarifying a doubt that I have regarding how Node.js executes timers. Normally when having a setTimeout block in your node script, the event loop, even if does not have anything else will wait for specified milliseconds in setTimeout and exits once it has run the callback.
But consider below code
const fs = require('fs');
let readable = fs.createReadStream('large.csv');
readable.on('data', async chunk => {
let rows = parseCsvRow(chunk);
try {
for (let i = 0; i < rows.length; i++) {
console.log(i);
await someAsyncOperation(rows[i]);
}
} catch (error) {
//something went wrong
}
});
readable.on('end', chunk => {
console.log('csv file processed successfully');
});
function someAsyncOperation(){
return new Promise((resolve, reject) => {
setTimeout(resolve, 2000);
});
}
The csv file I am reading has about 300 rows and I am firing an ajax request for each(code hidden for simplicity) which takes about 100ms to run and i have simulated it here using a setTimeout.
When I run above program it exits almost instantly without waiting for all pending setTimeout timers to run successfully. Just because the timers where scheduled from inside a data
event on read stream does event loop ignore it ? Should not it wait for all timers to execute ?
Note - I understand that above code is not the right way to do what I am doing but this is just a sample to demonstrate the concept that I am having a hard time understanding.