0

I've make a translation service in nodejs :

module.exports = {GetcountryFR, GetRegionFR, GetChildrenFR, GetHomeownFR, GetHomestyleFR, GetIncomeFR, GetLstatusFR, GetWdomainFR, GetWtypeFR, GetSexFR}

async function GetcountryFR(country) {
    var countrix = country;
    switch (countrix) {
        case 'createuser.france': countrix = 'FRANCE'; break;
        case 'createuser.belgique': countrix = 'BELGIQUE'; break;
        default: countrix = 'UNKNOWN'; break;
    }
    return countrix;
}

And now I make a function which uses translat function

const translate = require('../services/translate');

exports.AllUserToCSV = async function CSV() {
  try {
    let user = User.find();
    var data = [];
    len = user.length;
    for (i = 0; i < len; i++) {
      let sexix = await translate.GetSexFr(user[i].sex);
      let regionix = await translate.GetRegionFR(user[i].region);
      let countrix = await translate.GetcountryFR(user[i].country);
      let wtypix = await translate.GetWtypeFR(user[i].wtype);
      let wdomainix = await translate.GetWdomainFR(user[i].wdomain);

      temp = {
        sex: sexix,
        region: regionix,
        country: countrix,
        wtype: wtypix,
        wdomain: wdomainix,
      }
      data.push(temp);
    }
    const csvData = csvjson.toCSV(data, { headers: 'key' })
    filename2 = '/assets/media/' + 'TEST' + '.csv';
    writeFile(filename, csvData, (err) => {
      if (err) {
        console.log(err); // Do something to handle the error or just throw it
        throw new Error(err);
      }
      console.log('Success!');
    });
  } catch (e) {
    console.error(e);
  }

}

In results CSV file is Empty [].

If I put values in temp it's OK.

Why my translate function didn't work ??

Thanks for Help Good Friends :)

BenYsil
  • 137
  • 4
  • 16
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kunal Mukherjee Dec 10 '19 at 16:31

1 Answers1

0

Simply await your call to the User model i.e let user = await User.find();

Also for the loop, try

let users = await User.find(); await Promise.all(users.map(async (user) => { let sexix = await translate.GetSexFr(user.sex); ... })));

Writing to file, you may want to use await fs.writeFile(...);. This will make sure file is written before processing the next.

Olumide Oduola
  • 328
  • 2
  • 4