类变量未定义...尽管已定义

时间:2020-02-15 02:50:52

标签: coffeescript node-postgres

我有一个名为RouteBinder的类,如下所示:

    binder = new RouteBinder server, pool

    binder.bindRoute "login", controllers.login

我声明它并这样称呼它:

node-postgres

(池是 pool = new Pool [...] try client = await pool.connect() await client.query 'SELECT 1=1' catch e console.fatal "Could not connect to database: #{e}" return finally try client.release() if client? catch e console.fatal "Couldn't release client: #{e}" return console.info 'Database is OK!' 的池,并且像这样早先声明和测试)

 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
    at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
    at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
    at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12
    at /home/vi/[redacted]_accounts/main.js:166:26
 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
 02/14 18:44:34   error   (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

运行此命令时,出现此错误:

{
  "presets": ["@babel/env"],
  "plugins": [
    ["@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

我正在使用Babel转译的CoffeeScript编译。我的.babelrc看起来像这样:

Hmisc

很抱歉,如果这是一个菜鸟问题,我仍在学习,并且希望得到我能得到的所有建议。

1 个答案:

答案 0 :(得分:0)

我发现了我的错误。 @pool@server均已定义,但是@server[method]的内联函数(处理程序)在该函数的上下文中运行。

解决方案是使用.bind(@)(如果愿意,可以使用.bind(this))将其绑定到RouteBinder实例

    bindRoute: (name, fn, method = "post", useDb = true) ->
        @server[method]("/api/accounts/v1/" + name, ((req, res, next) ->
            console.log "pool", @pool
            client = await @pool.connect() if useDb?
            await fn req, res, next, client
            await @pool.release() if useDb?
        ).bind(@))