0

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.

DreamBold
  • 2,727
  • 1
  • 9
  • 24
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Aurast Jan 03 '23 at 18:36
  • @Aurast no that's not the problem here. – Evert Jan 03 '23 at 18:46

1 Answers1

0

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;
        }
  }
Yatin Gupta
  • 653
  • 5
  • 12
  • Thanks for your comment! it seems like using try/catch is really more correct. But now, the array named cities is empty, so it doesn`t recieve any data from db at all. However, this empty array passes to api. I`ll try to debug my db requests... – Александр Сосо Jan 03 '23 at 18:53