Skip to content

Instantly share code, notes, and snippets.

@dmcghan dmcghan/db-config.js
Created Jul 13, 2017

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`,
outFormat: oracledb.OBJECT
console.log('Query executed');
} catch (err) {
console.log('Error occurred', 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);
} catch (err) {
console.log('Opps, an error occurred', err);
"name": "async-functions",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"keywords": [],
"author": "Dan McGhan <> (",
"license": "ISC",
"dependencies": {
"oracledb": "^1.13.1"

This comment has been minimized.

Copy link
Owner Author

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.


This comment has been minimized.

Copy link

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
You can’t perform that action at this time.