Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Owner

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

This comment has been minimized.

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?

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