0
function cycle_Profiles(){
  const fs = require('fs')
  fs.readFile('src/data/profileInfo.json',function(err,data_array){
    if(err){
    alert(err);
   }
  var json = JSON.parse(data_array);
  //returns the JSON array of profiles
  return json;
 });
}

so im trying get this json data from this function to a variable in another function but im not sure exactly how to do it the return method won't work I was recommended doing it with a promise or async but im not too sure how to do that

2 Answers2

1

Return a Promise from the function and resolve it once you read the JSON data.

function cycle_Profiles() {
  const fs = require("fs");
  return new Promise((resolve, reject) => {
    fs.readFile("src/data/profileInfo.json", function (err, data_array) {
      if (err) {
        // reject if you get an error
        reject(err);
      }
      var json = JSON.parse(data_array);
      // resolve once you get the data
      resolve(json);
    });
  });
}

Use async/await or then/catch while invoking the function.

cycle_Profiles()
  .then(json => console.log(json))
  .catch(err => alert(err)); // alert here
Sahil Lamba
  • 96
  • 2
  • 6
0
const profile_data = fs.readFileSync(__dirname + '/data/profileInfo.json',(err,data)=>{});

profile_data_array = JSON.parse(profile_data)

this the fix I ended up using but comment above is good too