Skip to content

Instantly share code, notes, and snippets.

@dmcghan
Created July 13, 2017 01:08
Show Gist options
  • Save dmcghan/c3c4b43c592c1e37532546f58f4f8033 to your computer and use it in GitHub Desktop.
Save dmcghan/c3c4b43c592c1e37532546f58f4f8033 to your computer and use it in GitHub Desktop.
How to get, use, and close a DB connection using async functions
module.exports = {
user: 'hr',
password: 'oracle',
connectString: 'localhost:1521/orcl',
poolMax: 20,
poolMin: 20,
poolIncrement: 0
};
const oracledb = require('oracledb');
function getEmployee(empId) {
return new Promise(async function(resolve, reject) {
let conn; // Declared here for scoping purposes.
try {
conn = await oracledb.getConnection();
console.log('Connected to database');
let result = await conn.execute(
`select *
from employees
where employee_id = :emp_id`,
[empId],
{
outFormat: oracledb.OBJECT
}
);
console.log('Query executed');
resolve(result.rows[0]);
} catch (err) {
console.log('Error occurred', err);
reject(err);
} finally {
// If conn assignment worked, need to close.
if (conn) {
try {
await conn.close();
console.log('Connection closed');
} catch (err) {
console.log('Error closing connection', err);
}
}
}
});
}
module.exports.getEmployee = getEmployee;
const oracledb = require('oracledb');
const dbConfig = require('./db-config.js');
const employees = require('./employees.js');
async function startApp() {
try {
await oracledb.createPool(dbConfig);
let emp = await employees.getEmployee(101);
console.log(emp);
} catch (err) {
console.log('Opps, an error occurred', err);
}
}
startApp();
{
"name": "async-functions",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Dan McGhan <dan.mcghan@oracle.com> (https://jsao.io/)",
"license": "ISC",
"dependencies": {
"oracledb": "^1.13.1"
}
}
@UlrichGiorgioJaeger
Copy link

this is not installing dependencies why bother to provide a package json when not providing db useless

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment