0

I have a asynchronous function (a promise), which reads an xml file and give a map of keys and value, if the promise is resolved. I need this map throughout my project. So i want to read this xml file only once, probably at the start of my project and save the map in a variable. And i want to use the variable in different files of my project. Is there any way by which i can achieve this?

1 Answers1

0

You can define the functions in files to expect a parameter, use Promise.all() to load the files, pass the function reference from requested files to .then() within .then() chained to Promise.all()

const promise = Promise.resolve("do stuff");

promise.then(res => {
  Promise.all([fetch("loadFile1.js").then(res => res.text())
  /* , fetch("loadFile2.js")*/])
    .then(function(files) {
      let script = document.createElement("script");
      script.textContent = files[0];
      document.body.appendChild(script);
      promise.then(loadFile)
    })
});

where loadFiles1.js contains a function loadFile

function loadFile(data) {
  console.log(data);
}

plnkr http://plnkr.co/edit/SQzakbP936rEgnEzsP8R?p=preview

guest271314
  • 1
  • 15
  • 104
  • 177
  • This sounds like an implementation of a module loader, not the xml cache that the OP asked about. – Bergi Jul 23 '17 at 21:54
  • @Bergi _"This sounds like an implementation of a module loader, not the xml cache that the OP asked about."_ How so? `promise` returns the XML the OP inquires about having access to throughout code - after loading _"And i want to use the variable in different files of my project"_ – guest271314 Jul 23 '17 at 21:56
  • @Bergi Not too familiar with terms used to describe code. The code at Answer should perform both parts of requirement described at OP. – guest271314 Jul 23 '17 at 22:03
  • I believe this solution is backwards. The OP probably already has a system in place that loads the various files of the project. Also it doesn't scale well with individual dependencies - your code only works if all files depend only on the single `promise`. – Bergi Jul 23 '17 at 22:31
  • @Bergi No, the solution is not backwards. Perhaps you are reading the requirement backwards. The entire premise of the Question is that OP needs a variable to be defined which references XML. The XML needs to come first, then OP can load other files. Or, the files do not do stuff until the `Promise` which fetches XML is fulfilled. Yes, all other files do depend on the variable referencing the XML to be defined first _" I need this map throughout my project. So i want to read this xml file only once, probably at the start of my project and save the map in a variable."_ – guest271314 Jul 23 '17 at 22:37
  • @Bergi If you post an Answer given your interpretation of the requirement the OP will surely have a solution, from either perspective – guest271314 Jul 23 '17 at 22:41