无法使用节点从数据存储中检索数据

时间:2019-01-22 18:56:16

标签: node.js express google-cloud-datastore

我有一个使用node构建的简单get请求,表示从数据存储区检索数据。我无法获得结果。 “获取”请求异步调用被卡住。不知道发生了什么。

const express = require('express');
const {Datastore} = require('@google-cloud/datastore');

const app = express();

// Your Google Cloud Platform project ID
const projectId = 'xxx';

// Creates a client
const datastore = new Datastore({
  projectId: projectId,
  keyFilename: '/Masters-LUC/spring-2019/internship/service-keys/xxx.json'
});

const query = datastore
  .createQuery('approvals')
  .filter('status', '=', 'yes');

app.get("/api/get", (req, res, next) => {
  query.run().then(([documents]) => {
    documents.forEach(doc => console.log(doc));
  });

});

module.exports = app;

我使用异步功能重新编写了相同的内容。下面正在工作。为什么不以上呢?

// Retrieve data from datastore
async function quickStart() {
  // Your Google Cloud Platform project ID
  const projectId = 'xxx';

  // Creates a client
  const datastore = new Datastore({
    projectId: projectId,
    keyFilename: '/Masters-LUC/spring-2019/internship/service- 
keys/xxx.json'
  });

  const query = datastore
  .createQuery('approvals')
  .filter('status', '=', 'yes');

  const [approvals] = await datastore.runQuery(query);
  console.log('Tasks:');
  approvals.forEach(task => console.log(task));
}
quickStart().catch(console.error);

2 个答案:

答案 0 :(得分:0)

我注意到这两个功能在两个功能之间是不同的。在第一个中,您可以在函数调用之间重用查询对象。查询对象不应重复使用。

我注意到的第二件事是,您不使用传递到函数参数app.get()中的res。

答案 1 :(得分:0)

修改后的工作代码-

    app.get("/api/approvals/", (req, res, next) => {
    const query = datastore
    .createQuery('approvals');

    query.run().then((approvals) => {
    approvals.forEach(appr => console.log(appr)); // This is used to log results on console for verification

    // loading results on the response object to be used later by client
    res.status(200).json(
      {
        message: "Request was processed successfully!",
        approvals : approvals
      }
    );
  })
})
相关问题