jedi-java jedi-java - 9 months ago 30
Node.js Question

Undefined results when using imported custom nodejs module

I am trying to search my local db for a user by email, but when I try to reference a function that does that from a different js file, via an import, I get undefined results. I have searched a bit on Stack about this issue I am having, and heard of something referred to as a callback, is this something that I would need to implement? If so could you point me to an example ?

Thanks in advance!

Here is my code that is exported (db.js file) :

var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
exports.findEmail = (email) => {
// console.log('hi');
session
.run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
email: email
})
.then((result) => {
let result_string = '';

result.records.forEach((record) => {
console.log(record._fields);
result_string += record._fields + ' ';

});
return result_string;
})
.catch((e) => {
return ('error : ' + JSON.stringify(e));
})
}


Here is my code calling the export : (test.js)

var tester = require('./db.js');
let temp = tester.findEmail("testemail@yahoo.com");
console.log(temp);

Answer Source

The thing is that JS is asynchronous, and you using it as it is synchronous code.

Can you try this one, should work:

   var neo4j = require('neo4j-driver').v1;
   var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
   var session = driver.session();
   const findEmail = (email, callback) => {
   console.log('hi :', email);
   session
     .run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
      email: email
  })
  .then((result) => {
      let result_string = '';

      result.records.forEach((record) => {
          console.log(record._fields);
          result_string += record._fields + ' ';

      });
      return callback(null, result_string);
  })
  .catch((e) => {
      return callback('error : ' + JSON.stringify(e)));
   })
  }

 module.exports = {
     findEmail
 };

Then in test.js:

var tester = require('./db');
tester.findEmail("testemail@yahoo.com", (err, temp) => {
 if (err) return console.error(err);
 console.log(temp); 
} );

The idea behind this is that all the flow in db file is asynchronous.

So in order to catch result you need to pass the function, callback, which will be triggered when the ansynchronous flow is done.