How to refactor this code to use Promises for asyncronous functionality

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}`)

    var folderNameCSV = uuidv1()
    folderNameCSV = 'CSV_TO_JSON'
    fetchPage(csv, (error, data) => {

        if (error) return console.log(error)
        fs.writeFileSync(path.join(__dirname, folderNameCSV, 'file.xml'), data)


function transform(){
    .then((jsonObj) => {

        var folderNameJSON = uuidv1()
        folderNameJSON = 'JSON_CONVERTED'

        jsonObj = JSON.stringify(jsonObj)
        fs.writeFileSync(path.join(__dirname, folderNameJSON, 'archivo.json'), jsonObj)


My crappy approach :sweat_smile::joy::

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.

There are a number of options. Among them, you could use promises like you suggested, eg in downloadCSV

return new Promise((resolve, reject) => {
// call resolve() when you're done
// or call reject() when something fails.

Perhaps read mdn docs on Promise if you’re unfamiliar.

You can also use an async version of writeFile and pass an appropriate callback (your transform). Node docs on fs.writeFile