0
const xml2json = require("xml-to-json");    

const convertXMITOJSON = () => {
      xml2json(
        {
          input: "./sequence_diagram.xmi",
          output: "./test.json",
        },
        function (err, result) {
          if (err) console.error(err);
          else {
            return result;
          }
        }
      );
    };

let result = convertXMITOJSON();

console.log(result); // undefined

I want to use the value of result outside of this function. But when I return the value of result, it's getting undefined. Why is in this code the value of result outside the function undefined?

  • 1
    asynchronous calls 101 https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello May 07 '20 at 19:24
  • @AluanHaddad yes this is same type of question but can you please write code for this! I am unable to write the code by taking reference of above question. – Mayur Aitavadekar May 08 '20 at 10:27
  • @epascarello , I couldn't write a code after reading the the answer for that question. Can you please give code for my problem? – Mayur Aitavadekar May 08 '20 at 10:38
  • What are you struggling with? This isn't a code writing service. Hint: the result is the second parameter to your callback function (`function (err, result) {...}`). You must move all logic that involves the result into your existing callback and access it as that parameter. – Aluan Haddad May 08 '20 at 11:01
  • @AluanHaddad I was just confused about the use of promise with reject and resolve, I didn't work with that earlier. thanks for the response. – Mayur Aitavadekar May 08 '20 at 17:36
  • You don't actually need to create a promise wrapper. It's a reasonable approach though – Aluan Haddad May 08 '20 at 18:06

1 Answers1

0

Promises are the easiest way to deal with it

const xml2json = require("xml-to-json");

const convertXMITOJSON = () => {
  return new Promoise((resolve, reject) => {
    xml2json({
        input: "./sequence_diagram.xmi",
        output: "./test.json",
      },
      function(err, result) {
        if (err) {
          console.error(err);
          reject(err)
        } else {
          resolve(result);
        }
      }
    );
  })
};

convertXMITOJSON().then(result => {
  console.log(result);
}

The code could be changed with async and await

epascarello
  • 204,599
  • 20
  • 195
  • 236