Переменная класса не определена ... несмотря на то, что она определена - PullRequest
0 голосов
/ 15 февраля 2020

У меня есть класс с именем RouteBinder, который выглядит следующим образом:

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

Я объявляю его и называю так:

    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.

Я использую CoffeeScript, скомпилированный с Babel. Мой .babelr c выглядит так:

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

Извините, если это вопрос ладьи ie, я все еще учусь и буду рад всем советам, которые я смогу получить.

1 Ответ

0 голосов
/ 15 февраля 2020

Я понял свою ошибку. И @pool, и @server были определены, однако встроенная функция (обработчик) для @server[method] выполнялась в контексте этой функции.

Решением было связать ее с экземпляром RouteBinder с помощью .bind(@) (или .bind(this), если хотите)

    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(@))
...