The default programming approach in Node.js is using callbacks/event handlers. This is because even the different parts of a database request (connection, prepared statement, execution, etc) are all non-blocking operations.
Hint: A callback is an asynchronous operation that gets executed after another one notifies completion.
Add a second route handler, called example2
, that uses the async
module:
var async = require("async");
//Simple Database Select Via Client Wrapper/Middelware - Async Waterfall
app.get("/example2", (req, res) => {
let client = req.db;
async.waterfall([
function prepare(callback) {
client.prepare(`SELECT SESSION_USER, CURRENT_SCHEMA
FROM "DUMMY"`,
(err, statement) => {
callback(null, err, statement);
});
},
function execute(err, statement, callback) {
statement.exec([], (execErr, results) => {
callback(null, execErr, results);
});
},
function response(err, results, callback) {
if (err) {
res.type("text/plain").status(500).send(`ERROR: ${err.toString()}`);
} else {
var result = JSON.stringify({
Objects: results
});
res.type("application/json").status(200).send(result);
}
return callback();
}
]);
});
Take a look at both newly-added examples. You can easily notice that the second one is easier to read, although the runtime does not change. You can check for more information on the async
module in the async
documentation.