Home > Net >  Why does my recieved from database data is undefined?
Why does my recieved from database data is undefined?

Time:01-04

I`m creating API on my express.js server, so when it takes "get" request, some function placed in module file asking data from graph db:

module.js file:


function getGraphData() {
  const cityName = 'Milan';
  const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`;
  const cities = [];
  session
    .run(readQuery, { cityName })
    .then(function (result) {     
      result.records.forEach(function (record) {
        cities.push({
          title: record._fields[0].properties.name,
        });
      });
      return cities;
    })
    .catch((err) => console.log(err));
}
module.exports.getGraphData = getGraphData;

After receiving data it stores in array named cities and looks like this:

cities: [ { title: 'City1' }, { title: 'City2' }, { title: 'City3' } ]

So, function is returning this array, and then I import function from module and use it in my router file:

const { getGraphData } = require('./../db/neo4j');

router.get('/', async (req, res) => {
  try {
    const p = await getGraphData();
    console.log('p:', p); //p is undefined
    //return res.status(200).send(p); 
    return res.status(206).json(p); // empty response, not any data only status code
  } catch (e) {
    console.log(e); 
});

So, what I'm doing wrong? Why does api response is empty?

Im use debugger. Data realy comes to function in module, but doesn`t passing to api response to "p" variable.

CodePudding user response:

Your getGraphData function is using .then . When it executes it makes the session call and returns immediately that is why it returns empty.

Although, you are doing await on getGraphData, your getGraphData function needs to be defined as async and use await with session for it to work.

    async function getGraphData() {
      const cityName = 'Milan';
      const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`;
      const cities = [];
      try{
          const result = await session.run(readQuery, { cityName });
          result.records.forEach(function (record) {
                cities.push({
                  title: record._fields[0].properties.name,
                });
              });
          return cities;
        }
        catch(err){
           console.log(err);
           return err;
        }
  }
  • Related