node.js - ClaudiaJS 和 pg-pool : how to wrap in promise

标签 node.js aws-lambda node-postgres claudiajs

我使用 ClaudiaJS 部署无服务器 API(Lambda + API Gateway)。在我的 API 中,我使用 pg-pool 访问 RDS Postgres。

我做了什么:

在 app.js 中

var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();
module.exports = api;

var Pool = require('pg-pool');

api.get("/list", function (request) {
   var dbconnect = {
     user: ‘xxxx’, //env var: PGUSER
     database: ‘xxxx’, //env var: PGDATABASE
     password: ‘xxx’, //env var: PGPASSWORD
     host: ‘xxxxxxxxxx.eu-west-1.rds.amazonaws.com', // Server hosting the postgres database
     port: 5432, //env var: PGPORT
     max: 1,
     min: 0,
     idleTimeoutMillis: 300000, 
     connectionTimeoutMillis: 1000
};

var pool = new Pool(dbconnect)
var sql = ‘Select …’

pool.query(sql, function (err, result) {

    console.log('Lambda :: execute query ');

    var resp = new Object();
    var jsonArr = []; // Populate the result
    console.log('Lambda :: result :: ' + JSON.stringify(result));
    return JSON.stringify(result)
});
}

什么问题: 它不会返回任何内容,Cloudwatch 也不会显示任何错误。我用谷歌搜索了一下,人们说它没有包含在 Promise 中。我的问题是如何在这种情况下将 pg-pool 包装在 Promise 中。

如有任何建议,我们将不胜感激。谢谢

****更新****

我尝试在池中使用 promise

pool.connect().then(client => {
  client.query(sql).then(res => {
    client.release()
    console.log('Result:', res.rows[0])
    return JSON.stringify(res.rows[0]);
  })
  .catch(e => {
    client.release()
    console.error('query error', e.message, e.stack)
  })
})

我收到来自 CloudWatch 的错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Connection terminiated due to connection timeout

最佳答案

看起来你可以从 pool.query 得到一个 promise :

pg-pool supports a fully promise-based api for acquiring clients

https://github.com/brianc/node-pg-pool#acquire-clients-with-a-promise

然后您可以链接 promise 以返回 JSON:

return pool.query(sql).then(function (result) {

    console.log('Lambda :: execute query ');

    var resp = new Object();
    var jsonArr = []; // Populate the result
    console.log('Lambda :: result :: ' + JSON.stringify(result));
    return JSON.stringify(result)
}, function(error){
    //handle error here
    console.error(error);
});

关于node.js - ClaudiaJS 和 pg-pool : how to wrap in promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452737/

相关文章:

node.js - 构建聊天应用程序 : How to get time

amazon-web-services - API Gateway lambda 授权方自定义状态代码

amazon-web-services - AWS 云形成 : "The key pair ___ does not exist" error for newly-created EC2 key pair

node.js - 如何在 AWS Lambda 中使用 Node pg?

sql - 从查询中排除 "grouped"数据

angularjs - 在 IIS 上部署 Angular 应用程序

node.js - 使用 Angular 2(+) 和 Node/Express 服务器设置所有 TypeScript 项目

aws-lambda - 使用 Amplify 为 AppSync 自动化 Lambda 解析器?

node.js - 运行 Heroku Node.js 入门示例时遇到错误 - 数据库部分

javascript - 在 Nodejs/Express 中链接 promise 的最佳实践