简体   繁体   English

Promise.all() 连接到数据库时抛出错误 Error: timeout exceeded when used with Node-Postgres

[英]Promise.all() throwing error while connecting to database Error: timeout exceeded when used with Node-Postgres

I have Node.js express app with Postgres as a database.我有 Node.js Express 应用程序,以 Postgres 作为数据库。 I'm using pg for database communication from the app.我正在使用pg从应用程序进行数据库通信。

This is how my db.service looks like这就是我的db.service样子

import { Pool } from 'pg';

const dbConfig = {/*my valid db configuration*/};

const pool = new Pool(dbConfig);

export const connectDB = async () => {
 let client;
 try {
  client = await pool.connect();
 } catch (error) {
  console.error('error while connecting to database', error);
  process.exit(1);
 }
 return client;
};

I have two queries as below我有两个查询如下

#1. #1。

export const fetchUser = async (email) => {
const client = await connectDB();

  const query = `
    SELECT full_name FROM app.users
    WHERE  email = '${email}'
  `;

  let result;
  try {
    result = await client.query(query);
    if (result.rowCount) {
      return result.rows[0].full_name;
    }
  } catch (error) {
  } finally {
    await client.release();
  }
  return result;
};

#2 #2

export const fetchWallet = async (email) => {
    const client = await connectDB();
    
      const query = `
        SELECT wallet_money FROM app.user_wallet
        WHERE  email = '${email}'
      `;
    
      let result;
      try {
        result = await client.query(query);
        if (result.rowCount) {
          return result.rows[0].wallet_money;
        }
      } catch (error) {
      } finally {
        await client.release();
      }
      return result;
    };

Now from one of my controller.js if I call these function separate await, no issues现在从我的 controller.js 之一,如果我调用这些 function 单独等待,没有问题

ctrl.js Ctrl.js

   const fullName = await fetchUser('some@gmail.com');
   const walletMoney = await fetchWallet('some@gmail.com');

No issues this way, however if I merge them into a single promise这样没有问题,但是如果我将它们合并成一个 promise

   const $0= fetchUser('some@gmail.com');
   const $1= fetchWallet('some@gmail.com');
  
   const result = await Promise.all([$0, $1]);

this throws the below error这会引发以下错误

error while connecting to database Error: timeout exceeded when trying to connect at Error连接到数据库时出错错误:尝试连接时超时超时错误

Please suggest why this error is popping up & how can I get rid of it?请建议为什么会弹出此错误以及如何摆脱它?

Thanks!谢谢!

That's happening because you are trying to connect to DB separately for every query.Try to create one connection and use it for all queries!发生这种情况是因为您试图为每个查询分别连接到数据库。尝试创建一个连接并将其用于所有查询!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM