我正在try 通过GraphQL解析器返回Postgres DB查询.出于某种原因,当我(故意)查询一行不存在的ID时,result返回为未定义.当我记录它时,result总是按预期返回:

result = {
 rows: [],
 ...
}

然而,当我运行它并进行查询时,或者当我使用node inspect index.js并让它一直运行到调试器时,它似乎没有意识到result已经定义.当我在 node 中运行console.log(result)时,当它点击调试器时,我得到以下错误:

debug> console.log(result)
REPL2:1
console.log(result)
            ^

Uncaught ReferenceError: result is not defined
    at REPL2:1:13
    at Script.runInContext (node:vm:139:12)
    at Object.runInContext (node:vm:289:6)
    at REPLServer.controlEval (node:internal/debugger/inspect_repl:578:25)
    at bound (node:domain:421:15)
    at REPLServer.runBound [as eval] (node:domain:432:12)
    at REPLServer.onLine (node:repl:898:10)
    at REPLServer.emit (node:events:527:28)
    at REPLServer.emit (node:domain:475:12)
    at [_onLine] [as _onLine] (node:internal/readline/interface:424:12)

当我在操场上运行查询时,我得到以下错误:

/Users/user/Projects/geolocatr_api/db/queries/user.queries.js:21
          id: user.id,
                   ^

TypeError: Cannot read properties of undefined (reading 'id')
    at /Users/user/Projects/geolocatr_api/db/queries/user.queries.js:21:20
    at Query.<anonymous> (/Users/user/Projects/geolocatr_api/node_modules/pg-pool/index.js:417:18)
    at Query.handleReadyForQuery (/Users/user/Projects/geolocatr_api/node_modules/pg/lib/query.js:138:12)
    at Client._handleReadyForQuery (/Users/user/Projects/geolocatr_api/node_modules/pg/lib/client.js:290:19)
    at Connection.emit (node:events:527:28)
    at /Users/user/Projects/geolocatr_api/node_modules/pg/lib/connection.js:114:12
    at Parser.parse (/Users/user/Projects/geolocatr_api/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.<anonymous> (/Users/user/Projects/geolocatr_api/node_modules/pg-protocol/dist/index.js:11:42)
    at Socket.emit (node:events:527:28)
    at addChunk (node:internal/streams/readable:324:12)

Node.js v18.0.0
error Command failed with exit code 1.

我真的不知道为什么我的控制台日志(log)似乎看到了一些东西,但Node没有.否则,当传入表中存在的ID时,它会按预期工作.

代码:

// Resolver

  Query: {
    user: ( _, { id } ) => {
      console.log({id}); // Node recognizes this as the correct number
      return getUserById(id);
    },
  },


// DB Query Function

const getUserById = (id) => {
  return new Promise(function(resolve, reject) {
    db.query(
      `
        SELECT id, first_name, email, phone
        FROM users
        WHERE id = $1;
      `,
      [id],
      function(err, result) {
        // debugger; // Result comes back as not defined
        if (!result.rows) { // Will not run this if block
          console.log(result.rows);
          reject("Could not find user.");
        }
        if (err) reject(err);
        const user = rows[0];

        resolve({
           id: user.id,
           firstName: user.first_name,
           email: user.email,
           phone: user.phone,
        });
      }
    );
  });
};

推荐答案

通常,对于这(err, result) => { ... }个回调,您会 Select err first,因为如果它是truthy,那么第二个参数很可能不会被定义.

您还应该在检测到错误后返回return,以防止执行回调的其余部分.

仅供参考,node-postgresl本机支持promise ,因此无需明确创建一个.下面我将您的代码翻译成一个异步函数,以利用这一点.

const getUserById = async (id) => {
  const { rows } = await db.query({
    text: "SELECT id, first_name as firstName, email, phone FROM users WHERE id = $1",
    values: [id],
  });

  // `rows` is always an array so check the length
  if (rows.length !== 1) {
    throw new Error(`Could not find user by id [${id}]`);
  }

  return rows[0];
};

Node.js相关问答推荐

MongoServelSelection错误:服务器 Select 在30000 ms后超时

如何使用Node.js、Express和Mongoose创建多个API

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

MongoDB的方面查询的Postgres类似功能

EJS ForEach循环标记

如何在Node.js的telegraf.js命令中添加参数?

动态设置元数据,无需重复请求 NextJS 13

在生产环境中,Nest实例启动时抛出不完整的导入错误

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

npm install 在 Mac 上的 Node-gyp 构建错误

当我try 从本地主机发布新产品时收到错误消息

如何防止 node.js 中的内存泄漏?

如何promise AWS JavaScript 开发工具包?

node_modules 中 .bin 文件夹的用途是什么?

将变量传递给nodemailer中的html模板

如何使用 Node.js、Express 和 Mongoose 进行身份验证?

tsconfig.json 中模块类型的区别

在单独的模块中定义 Mongoose 模型

node.js 服务器和 HTTP/2 (2.0) 与 express.js

使用 Node-sass 缩小 CSS