So I did last week the challenges of ES6 and I saw how promises work. Until now I have worked a lot with Javascript but the only thing I understood was how setTimeOut works.
Now I have the following code which first downloads a file, and then, converts that file into a json one.
Right now I have it working by setting a setTimeOut to the transform()
function so the downloadCSV()
function can finish before attempting to transform but that is so crappy, I wanted to use something professional to do this.
The problem is If i create a promise then the code inside doesn´t really get executed and I dont know how to pass a function to that promise (if it can be done). Also i imagine is not the best clean way to do this.
So my question is, how would you make this code asynchrous so the transform() function doesn´t get called until the file is download it? I dont care much if it´s not done with promises i just want to know what is the correct/clean way to do it.
// 1. Download the CSV:
const downloadCSV = (csv) => {
console.log('downloading csv file')
const fetchPage = (urlF, callback) => {
https.get(urlF, (response) => {
let buff = ''
response.on('data', (chunk) => {
buff += chunk
})
response.on('end', () => {
callback(null, buff)
})
}).on('error', (error) => {
console.error(`Got error: ${error.message}`)
callback(error)
})
}
var folderNameCSV = uuidv1()
folderNameCSV = 'CSV_TO_JSON'
fs.mkdirSync(folderNameCSV)
fetchPage(csv, (error, data) => {
if (error) return console.log(error)
fs.writeFileSync(path.join(__dirname, folderNameCSV, 'file.xml'), data)
})
}
function transform(){
csvtojsonV2().fromFile('./CSV_TO_JSON/file.xml')
.then((jsonObj) => {
var folderNameJSON = uuidv1()
folderNameJSON = 'JSON_CONVERTED'
fs.mkdirSync(folderNameJSON)
jsonObj = JSON.stringify(jsonObj)
fs.writeFileSync(path.join(__dirname, folderNameJSON, 'archivo.json'), jsonObj)
})
}
My crappy approach :
downloadCSV(csv)
setTimeout(transform, 3000);
Obviously i cannot do a setTimeout for that code because if the csv is too big or conection is too slow the code would break. Is a terrible approach.