Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Promise reference error

I'm getting a reference error saying check is not defined when I call check().then(function(employees) towards the bottom of my code and I;m not sure why. This happens when I call getAllEmployees();

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


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


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


    let check = function(){
        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(employees){
        console.log(employees);
    }).catch(function(){
        console.log("No results returned");
    });
}
like image 388
Workkkkk Avatar asked Aug 02 '26 15:08

Workkkkk


2 Answers

  • You forgot to capitalize Promise
  • Your code structure is terrible
  • Wrap legacy node async code in Promises
  • Defer error handling code to caller
  • import native node libs at root level (make them consts too)

Here is the refactored version:

const fs = require("fs");
const util = require("util");
const read = util.promisify(fs.readFile);

function init() {
    var reads = ["employees.json", "department.json"]
                .map(file => read(`./data/${file}`, "utf8").then(JSON.parse));

    return Promise.all(reads)
           .then(([employees, departments]) => ({ employees, departments }));
}

init().then(console.log).catch(console.error);
like image 170
Rafael Avatar answered Aug 04 '26 12:08

Rafael


Function check is not defined in the scope of getAllEmployees function, because you have defined check function as local function inside initialize function.

First weird thing:

function initialize(){
    var fs = require("fs");

Maybe it's best if you set all require modules at the top, not inside the function.


I did some modifications to your code, now you won't have that error:

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);
        //console.log(employees);
    });


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

function check() {
    return new promise(function(resolve,reject){
        if (error === 0){
            resolve("Success");
        }
        else if(error === 1){
           reject("unable to read file");
        }
    })     
};

function getAllEmployees(){
    initialize();
    check().then(function(employees){
        console.log(employees);
    }).catch(function(){
        console.log("No results returned");
    });
}

Summary of changes I did:

First, locate the main problem about you are asking, why are you getting "check function is not found"?. As I said in the beginning, check function was declared in the initialize scope function and getAllEmployees was declared outside so the main error is clear.

What I did: change initialize function to only get json data and set two global variables: employees and departments. Move check function to outside of initialize scope, as a module function to check promises.

Change getAllEmployees function to first, call initialize (to get json data and set the global variables) and call check function.

There are best ways to manage promises as for example the way provide as @Rafael in his answer.

like image 38
Kalamarico Avatar answered Aug 04 '26 11:08

Kalamarico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!