Node.Js为空数组

时间:2017-10-02 23:49:26

标签: javascript node.js

我有一个名为employees的全局数组,在我调用initialize();时会填充数据但是当我尝试在getAllEmployees()中打印数组时,员工的数组是空的,我不知道不知道为什么。数据被正确存储在intitialize();函数中,因为当我在employees函数中打印initialize();数组时,它充满了数据,所以我很困惑因为员工在全局名称空间中

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();

0 个答案:

没有答案