我正在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相关问答推荐

NX无法使用缓存运行根级脚本

Firebase-admin筛选器.或只考虑第一个WHERE子句

根据我的测试,为什么在编写Varint代码方面,NodeJS要比Rust快这么多?

如何将我的Redis客户端配置为在禁用群集模式的情况下使用读取副本?

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

我如何在nodejs中的路由之间交换令牌

在构建完成后,将AddedFiles文件夹的内容复制到dist文件夹

使用 Nodejs 获取 Firebase 云消息传递历史记录

Next.js 在我的电脑上没有构建错误,但它们在使用 Vercel 部署时发生

NPM 错误:修复upstream 依赖冲突安装 NPM 包(云功能)

如何在没有云功能的情况下使用 Google PubSub

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

mongoose 模式中的嵌套对象

在多个 .env 文件之间切换,例如 .env.development 和 node.js

用一级 try ... catch 捕获 JavaScript Promise 中的错误

PhoneGap/Cordova Android 开发

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

nodejs - 临时文件名

NodeJS / Express 中的module.exports和exports.methods是什么意思?

如何使用 Socket.io 防止 Node.js 中的分布式拒绝服务攻击?