I
I
Ivan2019-03-21 08:21:26
JavaScript
Ivan, 2019-03-21 08:21:26

How to use promise for this code?

var xml_file = fs.readFileSync('xml/jp/eshop_jp.xml', 'utf8');

xml2js(xml_file, function (err, result) {
    fs.writeFile('json/jp/eshop_jp.json', JSON.stringify(result,"",2), (err) => {
        if (err) {
          console.error(err);
          return;
         };
    });   
});

var eshop_jp = JSON.parse(fs.readFileSync('json/jp/eshop_jp.json', 'utf8'));

In my code, the last line is executed before xml2js is executed. Apparently, I need to use promises, but I don't know how to wrap my code in promises, what will resolve, what will be reject, how to call the next part of the code, and so on ... Please show me how to wrap the code in promises.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
ProjectSoft, 2019-03-21
@ivanxpru

like this

function readXmlFIle(file, jsonfile) {
  return new Promise(function(resolve, reject){
    var xml_file = fs.readFileSync(file, 'utf8');
    xml2js(xml_file, function (err, result) {
      if(err){
        reject(err);
        return;
      }
      fs.writeFile(jsonfile, JSON.stringify(result,"",2), function(error){
        if (error) {
          reject(error);
          return;
        };
        resolve();
      });   
    });
  });
}

readXmlFIle('xml/jp/eshop_jp.xml', 'json/jp/eshop_jp.json').then(function(){
  var eshop_jp = JSON.parse(fs.readFileSync('json/jp/eshop_jp.json', 'utf8'));
}).catch(function(err){
  console.log(err)
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question