0

I have a global array called employees that gets filled with data when I call initialize(); but when I then try to print the array in getAllEmployees() the employee's array is empty and I don't know why. The data gets stored properly in the intitialize(); function because when I print the employees array in the initialize(); function, it's filled with data, so I'm puzzled because employees are in the global namespace

var employees = [];
var departments = [];
var error = 0;
var fs = require("fs");

function initialize(){

fs.readFile("./data/employees.json", 'utf8', function(err, data){
    if(err){
        error = 1;
    }
    employees = JSON.parse(data);

});


fs.readFile("./data/department.json", 'utf8', function(err, data){
      if(err){
          error = 1;
      }
      departments = JSON.parse(data);

  });
}

function check() {
  return new Promise(function(resolve,reject){

      if (error === 0){
          resolve("Success");

      }
      else if(error === 1){
         reject("unable to read file");
      }
  })     
};

 function getAllEmployees(){

  check().then(function(x){
      console.log(x);
      console.log(employees);

  }).catch(function(x){
      console.log("No results returned");
  });
}

initialize();
getAllEmployees();
Duc Filan
  • 6,769
  • 3
  • 21
  • 26
Workkkkk
  • 265
  • 1
  • 5
  • 22
  • 1
    You're calling that promise way too soon. Have you tried using `promisify` to convert `readFile` to a promise-driven version? – tadman Oct 02 '17 at 23:53
  • no but that's not the problem. my empployees array is in the global namespace and gets filled when I call initialize, but it becomes an empty array when I call it in the promise. – Workkkkk Oct 02 '17 at 23:58
  • My error variable which is also in the global namespace works if I were to print it, but I have no idea why my employees array doesn't – Workkkkk Oct 03 '17 at 00:00
  • It's not about it being in the global namespace. It's a matter of time - `fs.readFile()` doesn't return it's value right away. By the time it does you have already called the console log in `getAllEmployees()`. That's the challenge of async programming. – Mark Oct 03 '17 at 00:00
  • I'll try calling it synchronously and will get back to you – Workkkkk Oct 03 '17 at 00:02
  • 1
    Pretend callbacks happen at some point in the distant future. You need to set up this code to handle that. Promisify the calls. – tadman Oct 03 '17 at 00:03
  • 1
    Brute-force sync calls are not the answer here. Promisification fixes it because then you can chain it in there properly. Your `check()` function should wait on those two callbacks to fire, as right now it doesn't. – tadman Oct 03 '17 at 00:03
  • 1
    If this is truly an init that needs to happen before your program can run you can consider `require()`ing the json files: `var employees = require('./data/employees.json')` or something similar. Require is synchronous. – Mark Oct 03 '17 at 00:05

0 Answers0