node.js - 将 Async/Await 与 node-postgres 一起使用

标签 node.js postgresql node-postgres

我正在使用 node-postgres 查询我的数据库,想知道如何使用 async/await 并正确处理错误

这里是我使用的一个非常简单的查询示例

const { Pool } = require('pg');

let config;
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
  config = { connectionString: process.env.DATABASE_URL, ssl: true };
} else {
  config = {
    host: 'localhost',
    user: 'myuser',
    database: 'mydatabase',
  };
}

const pool = new Pool(config);

async function getAllUsers() {
  let response;
  try {
    response = await pool.query('select * FROM users');
  } catch (error) {
    throw error;
  }
  return response.rows;
}

然后在我的 routes.js 中有

app.get('/all_users', async (req, res) => {
  const users = await queries.getAllUsers();
  console.log(users); // returns all users fine
});

到目前为止,这是我的理解,但我认为我没有正确处理这个问题,因为当涉及到错误时,我的应用程序将卡住并抛出 UnhandledPromiseRejectionWarning。例如,如果我提供了不正确的表格

async function getAllUsers() {
  let response;
  try {
    response = await pool.query('select * FROM notable');
  } catch (error) {
    throw error;
  }
  return response.rows;
}

UnhandledPromiseRejectionWarning: error: relation "notable" does not exist

应用程序将在 30 秒后崩溃,我没有妥善处理此错误。我错过了什么?

最佳答案

async 函数或 Promise 抛出 Uncaught Error 时,或者当 catcher 也抛出时,例如您的

throw error;

这意味着函数的调用者将面临被拒绝的 Promise 需要处理。如果您在调用方中使用 await,那么您还必须在调用方中使用 try/catch 才能正确捕获错误:

app.get('/all_users', async (req, res) => {
  try {
    const users = await queries.getAllUsers();
    console.log(users);
  } catch(e) {
    // handle errors
  }
});

无需在消费者中使用 try/catch 即可解决错误的另一种方法是不在 catchthrow 错误:

async function getAllUsers() {
  let response;
  try {
    response = await pool.query('select * FROM users');
    return response.rows;
  } catch (error) {
    // handle error
    // do not throw anything
  }
}

但这会使消费者更难知道何时出现错误。

在这种特殊情况下,async/await/try/catch 结构添加了很多语法没有太多好处的噪声 IMO - 目前,您可以考虑使用普通的 Promises:

const getAllUsers = () => pool.query('select * FROM users')
  .then(response => response.rows);

// and:
app.get('/all_users', (req, res) => {
  queries.getAllUsers()
    .then((users) => {
      console.log(users);
    })
    .catch((err) => {
      // handle errors
    });
});

asyncawait 当您有一些 .then 时您希望在您的代码中看起来更平坦。如果只有一个 .then,IMO 将其转换为 async/await 语法没有太大好处。当然,这取决于您。

关于node.js - 将 Async/Await 与 node-postgres 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910835/

相关文章:

php - 从 Node 服务器上传文件时 move_uploaded_file 始终返回 false

node.js - socket.io 不适用于传输 : [ 'xhr-polling' ]

node.js - Node 防止意外调用异步函数而不等待

ruby-on-rails - Rails 4 - 如何在 postgres 上存储数组

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

javascript - CORS请求问题(XMLHttpRequest)

sql - Oracle、Postgres 和 SQL Server 中的字符串连接运算符

json - 合并两个联接表并输出为 JSON?

node.js - 为什么我的 Promise 在某些情况下返回数据库行,而在其他情况下则不返回?

lambda - 使用 Ngrok 从 AWS Lambda 连接到本地 PostgreSQL