I would like to avoid using timeout to display the final result of a series of asynchronous operations. Without the setTimeout
when I print at the end of the while
, the array is empty. The problem is clear being asynchronous operations. I could not find an alternative solution to using the timeout while keeping the cb-style (without promise)
const fs = require('fs')
function leggi_file(){
let files = ['a','b','c','d']
let totale = []
while(true){
let file=files.shift()
if (file) fs.readFile(file,(err,data)=>{
if (err){
console.error(err)
return
}else totale.push(data)
})
else {
setTimeout(()=>console.log(totale),300)
break}
}
}
leggi_file()