I created a function to get an Oracle connection using oracledb, but in a few cases, oracledb didn't throw an exception even if he didn't get the connection, apparently he's trying to connect infinitely.
const getConnection = async (): Promise<oracledb.Connection | undefined> => {
let connection;
try {
connection = await oracledb.getConnection({
user: process.env.DB_LOGIN,
password: process.env.DB_PASSWORD,
connectString: process.env.DB_STRING_CONNECTION,
});
} catch (err) {
console.error(err);
}
return connection;
};
I saw a few samples using Promise.racing with setTimeout but i couldn't put it in pratice, my tries always get an UnhandledPromiseRejectionWarning on console so i think it isn't the correct way.
Can anybody show me an example how to do that?
Promise.race
should work fine if you implement it properly. Race the getConnection
against a Promise that resolves (not rejects), and make sure to chain to a .catch
.
const getConnection = (): Promise<oracledb.Connection | undefined> => {
return Promise.race([
oracledb.getConnection({
user: process.env.DB_LOGIN,
password: process.env.DB_PASSWORD,
connectString: process.env.DB_STRING_CONNECTION,
}),
new Promise((resolve) => { setTimeout(resolve, 5000); })
])
.catch((error) => {
// this will only be entered into if getConnection rejects (and not if it times out)
console.log(error);
})
};