Skip to content

Instantly share code, notes, and snippets.

@dmcghan
Created July 13, 2017 01:08
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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"
}
}
@dmcghan
Copy link
Author

dmcghan commented Jul 13, 2017

This gist is a demo app that shows how to get, use, and close a DB connection using async functions (a.k.a async/await). See the related blog post and the main post for the series for more details.

@vincentmorneau
Copy link

vincentmorneau commented Aug 29, 2017

For the sake of this example, should've we have getEmployee be an async function and have it return the variable result (from line 12)?

Why going through return new Promise(async function(resolve, reject) { and handling resolve/reject manually? Since async functions are always returning Promises, it would be redundant to do so. What do you think?

@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