为什么我从数据库接收到的数据是未定义的?

huangapple go评论77阅读模式
英文:

Why does my recieved from database data is undefined?

问题

I'm here to provide the translation you requested. Here's the translated content:

在我的express.js服务器上创建API时,当它接收到“get”请求时,会在模块文件中的某个函数中从图数据库中请求数据:

module.js文件:

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;

接收到数据后,它存储在名为cities的数组中,看起来像这样:

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

因此,该函数返回此数组,然后我从模块中导入函数并在我的路由文件中使用它:

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

那么,我做错了什么?为什么API响应为空?

我使用了调试器。数据确实传递到模块中的函数,但没有传递到API响应中的“p”变量。

英文:

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.

答案1

得分: 0

Your getGraphData function is using .then。当它执行时,它会进行会话调用并立即返回,这就是为什么它返回为空。

虽然你在getGraphData上使用了await,但你的getGraphData函数需要被定义为异步,并且在会话中使用await才能正常工作。

英文:

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;
        }
  }

huangapple
  • 本文由 发表于 2023年1月4日 02:17:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/74997189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定