![](/img/trans.png)
[英]Mocha Unit Test Timeout of 10000ms exceeded Error when using await Promise.all
[英]Promise.all() throwing error while connecting to database Error: timeout exceeded when used with Node-Postgres
我有 Node.js Express 應用程序,以 Postgres 作為數據庫。 我正在使用pg從應用程序進行數據庫通信。
這就是我的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;
};
我有兩個查詢如下
#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
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;
};
現在從我的 controller.js 之一,如果我調用這些 function 單獨等待,沒有問題
Ctrl.js
const fullName = await fetchUser('some@gmail.com');
const walletMoney = await fetchWallet('some@gmail.com');
這樣沒有問題,但是如果我將它們合並成一個 promise
const $0= fetchUser('some@gmail.com');
const $1= fetchWallet('some@gmail.com');
const result = await Promise.all([$0, $1]);
這會引發以下錯誤
連接到數據庫時出錯錯誤:嘗試連接時超時超時錯誤
請建議為什么會彈出此錯誤以及如何擺脫它?
謝謝!
發生這種情況是因為您試圖為每個查詢分別連接到數據庫。嘗試創建一個連接並將其用於所有查詢!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.