UnhandledPromiseRejectionWarning:未处理的promise promise(拒绝ID:22):ReferenceError:未定义客户端

时间:2017-05-25 01:36:18

标签: javascript node.js async-await try-catch

我发出的每个http请求似乎都会出现此错误。我不完全确定它来自哪里?

(node:39390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 22): ReferenceError: client is not defined

错误中没有行号,但这里有一个似乎导致它的代码示例:

try {
    var client = await pool.connect();
    await client.query(queryStatement, queryArgumentsArray);
    res.sendStatus(200);
} catch (e) {
    console.log('Error adding updating subvendor availability data, UPDATE SQL query task', err);
    res.sendStatus(500);
} finally {
    client && client.release && client.release();
}

首先我认为它必须来自我的finally块(可能client超出范围),但我添加了if语句以明确阻止尝试调用client.release如果它不存在:

if (client) { client && client.release && client.release() };

我仍然遇到这个错误,所以我觉得它必须来自这些方面。

var client = await pool.connect();
await client.query(queryStatement, queryArgumentsArray);
res.sendStatus(200);

我误解了如何使用异步?为了清楚起见,代码运行良好,http请求正在工作(正确响应请求),我的终端正在充斥着这些警告。

以下是完整路线的简化版本:

var express = require('express');
var router = express.Router();
var pool = require('../modules/pg-pool'); // brings in pg-pool created in another module

// This route updates the availability for a user
router.put('/updateAvailability', async (req, res) => {
    var userId = req.decodedToken.userSQLId;
    var subvendorId = req.headers.subvendor_id;
    var availability = req.body;

    var queryStatement = 'UPDATE status SET status=$3 WHERE userId=$2';
    var queryArgumentsArray = [availability.status, userId ];

    try {
        var client = await pool.connect();
        await client.query(queryStatement, queryArgumentsArray);
        res.sendStatus(200);
    } catch (e) {
        console.log('Error updating subvendor availability data, UPDATE SQL query task', err);
        res.sendStatus(500);
    } finally {
        client && client.release && client.release();
    }
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

此处的所有功劳都归brianc node-postgres的创建者{I} {}}} try-catch我的问题在我收到有关该库可能存在问题的建议之后回答了我的问题(似乎不是)。我只需要在var client = await pool.connect() try { await client.query(...) res.sendStatus(200) } catch { ...} finally { }

之外创建客户端
+s[1] || 0

 s[1]       take the character at index 1
+           use unary plus for converting string to number, this could return NaN
      || 0  in this case take zero instead of the falsey value, like NaN

他的完整答案可以在这里找到:https://github.com/brianc/node-postgres/issues/1301