Recursions on the tree structure in node.js - javascript

The task is to recursively build a tree-structure in node.js. Namely, I work with a deck of slides that might include also other subdecks. I am new to functional programming and I am stuck in understanding what I need to do. I know, there are much more advanced ways to control the flows, but I want for the beginning try to do it in a nested way, if it is possible. What I have for now:
The server.js calls an api and responds with a json object:
router.get('/deck/tree/:rev_id', function(req, res) {
var Deck = require('./models/deck');
var deck = new Deck(connection);
deck.getTree(req.params.rev_id ,function (tree) {res.json(tree)});
});
In the deck module I have several functions:
2.a Function to get the title of a deck:
this.getTitle = function(rev_id, callback){
var sql = "SELECT title FROM ?? WHERE ?? = ?";
var inserts = ['deck_revision', 'id', rev_id];
sql = mysql.format(sql, inserts);
connection.query(sql, function(err, results) {
if (err) throw err;
callback(results[0].title);
});
};
2.b Function to get the "direct" children of a deck:
this.getChildren = function(acc, callback){
acc.children = [];
var sql = "SELECT item_id AS id, item_type AS type FROM ?? WHERE ?? = ? ORDER BY position";
var inserts = ['deck_content', 'deck_revision_id', acc.id];
sql = mysql.format(sql, inserts);
connection.query(sql, function(err, results) {
if (err) throw err;
results.forEach(function(res_item){
acc.children.push({'id': res_item.id, 'type': res_item.type});
if (acc.children.length === results.length){
callback(acc);
}
});
});
};
Function that should buid the tree (does not work for now):
var results = [];
this.getTree = function(id, callback) {
var acc = {};
var deck = this;
var new_slide = new Slide(connection);
deck.getTitle(id, function (title_str) {
acc.title = title_str;
acc.id = id;
acc.type = 'deck';
deck.getChildren(acc, function(new_acc){
new_acc.children.forEach(function(element){
if (element.type === 'deck'){
// I suppose the help is needed here!
deck.getTree(element.id, function(new_element){
results.push(new_element);
if(results.length === new_acc.children.length) {
callback(results);
}
});
}else{
new_slide.getTitle(element.id, function(title_str){
element.title = title_str;
results.push(element);
if(results.length === new_acc.children.length) {
callback(results);
}
});
}

If somebody is interested, here how I/ve made it work:
this.getChildren = function(id, callback){
var sql = "SELECT item_id AS id, item_type AS type, position FROM ?? WHERE ?? = ? ORDER BY position";
var inserts = ['deck_content', 'deck_revision_id', id];
sql = mysql.format(sql, inserts);
connection.query(sql, function(err, results) {
if (err) throw err;
callback(results);
});
};
this.getTree = function(id, acc, callback) {
deck = new Deck(connection);
var new_slide = new Slide(connection);
deck.getTitle(id, function (title_str) {
acc.title = title_str;
acc.id = id;
acc.type = 'deck';
acc.children = [];
deck.getChildren(acc.id, function(children){
children.forEach(function(element){
if (element.type === 'deck'){
deck.getTree(element.id, element, function(new_element){
acc.children[new_element.position - 1] = new_element;
var size = acc.children.filter(function(value) { return value !== null }).length;
if (size === children.length){
callback(acc);
}
});
}
else{
new_slide.getTitle(element.id, function(title_str){
element.title = title_str;
acc.children[element.position - 1] = element;
var size = acc.children.filter(function(value) { return value !== null }).length;
if(size === children.length) {
callback(acc);
}
});
}
});
});
});
};

Related

how to call an array which is in a function from the another function in javascript?

This is the async function:
async function getpackages(conn, childId, callback) {
var childId = childId;
var request6 = new sql.Request(conn);
var packageQuery = "select OrderId,ChildID from dbo.tbl_Scheduler where NoOfMealsLeft>0 and ChildId=" + childId;
await request6.query(packageQuery, function (err, packagelist) {
if (!err && packagelist.recordsets.length > 0) {
console.log("Error:" + err + "Result:" + util.inspect(packagelist.recordsets[0]));
var orderdetail_ = [];
for (i = 0; i < packagelist.recordsets[0].length; i++) {
orderdetail_.push(packagelist.recordsets[0][i].OrderId);
}
console.log("-->" + orderdetail_);
callback(null, packagelist.recordsets[0]);
} else if (packagelist.recordsets.length < 1) {
callback("Not a valid id input", null);
}
});
};
I need to call the orderdetails_ array in the query. The array contains four data and I need to iterate over 4 data one by one, using the or in the SQL query.
module.exports.newscheduledmeal = function (req, res, next, callback) {
let entered_date = req.query.date;
let childId = req.query.id;
let current_date = new Date().toISOString().slice(0, 10);
if (entered_date < current_date) {
return callback('Please enter date more than or equal to current date.', null);
} else
var conn = new sql.ConnectionPool(dbConfig);
try {
conn.connect().then(function () {
var request = new sql.Request(conn);
getpackages(conn, childId, function (err, orderid) {
if (err) {
callback(err, null);
} else
var PackageidQuery = "select PackageId from dbo.tbl_Order where OrderId=";
request.query(PackageidQuery, function (err, packagelist) {
if (!err) {
conn.close();
callback(null, packagelist.recordsets);
} else {
conn.close();
callback("Error", null);
}
});
});
});
} catch (err) {
console.log("Exception occured:" + err);
conn.close();
callback(err, null);
}
};
I want to get the details of the array which is in getpackages to be used in the module section and specifically in the SQL query section.

Why is my code not waiting for the completion of the function?

I am trying to read some data from a file and store it in a database.
This is part of a larger transaction and I need the returned ids for further steps.
async parseHeaders(mysqlCon, ghID, csv) {
var self = this;
var hIDs = [];
var skip = true;
var idx = 0;
console.log("Parsing headers");
return new Promise(async function(resolve, reject) {
try {
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(csv)
});
await lineReader.on('close', async function () {
console.log("done: ", JSON.stringify(hIDs));
resolve(hIDs);
});
await lineReader.on('line', async function (line) {
line = line.replace(/\"/g, '');
if (line.startsWith("Variable")) { //Variable,Statistics,Category,Control
console.log("found variables");
skip = false; //Ignore all data and skip to the parameter description.
return; //Skip also the header line.
}
if (!skip) {
var data = line.split(",");
if (data.length < 2) { //Variable section done return results.
console.log("Found sub?",line);
return lineReader.close();
}
var v = data[0];
var bidx = data[0].indexOf(" [");
if (bidx > 0)
v = data[0].substring(0, bidx); //[] are disturbing mysql (E.g.; Air temperature [�C])
var c = data[2];
hIDs[idx++] = await self.getParamID(mysqlCon, ghID, v, c, data);//, function(hID,sidx) { //add data in case the parameter is not in DB, yet.
}
});
} catch(e) {
console.log(JSON.stringify(e));
reject("some error occured: " + e);
}
});
}
async getParamID(mysqlCon,ghID,variable,category,data) {
return new Promise(function(resolve, reject) {
var sql = "SELECT ID FROM Parameter WHERE GreenHouseID="+ghID+" AND Variable = '" + variable + "' AND Category='" + category + "'";
mysqlCon.query(sql, function (err, result, fields) {
if(result.length === 0 || err) { //apparently not in DB, yet ... add it (Acronym and Machine need to be set manually).
sql = "INSERT INTO Parameter (GreenHouseID,Variable,Category,Control) VALUES ("+ghID+",'"+variable+"','"+category+"','"+data[3]+"')";
mysqlCon.query(sql, function (err, result) {
if(err) {
console.log(result,err,this.sql);
reject(err);
} else {
console.log("Inserting ",variable," into DB: ",JSON.stringify(result));
resolve(result.insertId); //added, return generated ID.
}
});
} else {
resolve(result[0].ID); //found in DB .. return ID.
}
});
});
}
The functions above are in the base class and called by the following code:
let headerIDs = await self.parseHeaders(mysqlCon, ghID, filePath);
console.log("headers:",JSON.stringify(headerIDs));
The sequence of events is that everything in parseHeaders completes except for the call to self.getParamID and control returns to the calling function which prints an empty array for headerIDs.
The console.log statements in self.getParamID are then printed afterward.
What am I missing?
Thank you
As you want to execute an asynchronous action for every line we could define a handler to do right that:
const once = (target, evt) => new Promise(res => target.on(evt, res));
function mapLines(reader, action) {
const results = [];
let index = 0;
reader.on("line", line => results.push(action(line, index++)));
return once(reader, "close").then(() => Promise.all(results));
}
So now you can solve that easily:
let skip = false;
const hIDs = [];
await mapLines(lineReader, async function (line, idx) {
line = line.replace(/\"/g, '');
if (line.startsWith("Variable")) { //Variable,Statistics,Category,Control
console.log("found variables");
skip = false; //Ignore all data and skip to the parameter description.
return; //Skip also the header line.
}
if (!skip) {
var data = line.split(",");
if (data.length < 2) { //Variable section done return results.
console.log("Found sub?",line);
return lineReader.close();
}
var v = data[0];
var bidx = data[0].indexOf(" [");
if (bidx > 0)
v = data[0].substring(0, bidx); //[] are disturbing mysql (E.g.; Air temperature [�C])
var c = data[2];
hIDs[idx] = await self.getParamID(mysqlCon, ghID, v, c, data);
}
});

Searching two tables in one function in DynamoDB

I am trying to link two tables in DynamoDB for an Amazon Alexa skill. I am using two tables one is named 'yesno' and the other 'fixtures'. The fixtures table has a list of 22 names in each record and these names are in the 'yesno' table along with the column 'goals'. Here you can see the tables in more detail. Name Table:
Fixtures Table:
As you can see there are names that link the two databases together. I use the team1 column to search the fixtures table and use the name column to search the name table. Here is my code for searching:
function readDynamoItem(params2, callback) {
var AWS = require('aws-sdk');
AWS.config.update({region: AWSregion});
var dynamodb = new AWS.DynamoDB();
const names = new Array();
console.log('reading item from DynamoDB table');
dynamodb.scan(params2, function (err, data){
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
//tried to put a automatic loop for the long bit of code after this but didnt work so anyone with insight on this too would be helpful
/*for(var i = 1; i <= 11; i++){
var str = "T1S";
var pos = i.toString();
pos = str.concat(pos);
names[i] = jsonToString(data.Items[0].pos);
}
for(var j = 1; j <= 11; j++){
str = "T2S";
pos = j.toString();
pos = str.concat(pos);
names[(j+11)] = jsonToString(data.Items[0].pos);
}
*/
names[1] = jsonToString(data.Items[0].T1S1);
names[2] = jsonToString(data.Items[0].T1S2);
names[3] = jsonToString(data.Items[0].T1S3);
names[4] = jsonToString(data.Items[0].T1S4);
names[5] = jsonToString(data.Items[0].T1S5);
names[6] = jsonToString(data.Items[0].T1S6);
names[7] = jsonToString(data.Items[0].T1S7);
names[8] = jsonToString(data.Items[0].T1S8);
names[9] = jsonToString(data.Items[0].T1S9);
names[10] = jsonToString(data.Items[0].T1S10);
names[11] = jsonToString(data.Items[0].T1S11);
names[12] = jsonToString(data.Items[0].T2S1);
names[13] = jsonToString(data.Items[0].T2S2);
names[14] = jsonToString(data.Items[0].T2S3);
names[15] = jsonToString(data.Items[0].T2S4);
names[16] = jsonToString(data.Items[0].T2S5);
names[17] = jsonToString(data.Items[0].T2S6);
names[18] = jsonToString(data.Items[0].T2S7);
names[19] = jsonToString(data.Items[0].T2S8);
names[20] = jsonToString(data.Items[0].T2S9);
names[21] = jsonToString(data.Items[0].T2S10);
names[22] = jsonToString(data.Items[0].T2S11);
}
});
var goals = new Array();
//for loop to be used later when expanding
//for(var i = 1; i <= 22; i++){
var params = {
TableName: 'yesno',
FilterExpression: 'name = :value',
ExpressionAttributeValues: {':value': {"S": names[2]}}
};
dynamodb.scan(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
var temp = jsonToString(data.Items[0].goals);
goals[1] = temp;
}
callback(goals[1]);
});
//}
}
function jsonToString(str){
str = JSON.stringify(str);
str = str.replace('{\"S\":\"', '');
str = str.replace('\"}', '');
return str;
}
I am trying to use the goals array to print each persons goals off but right now it won't even print one persons and instead will print an undefined object of some sort. I'm guessing it just can't search the names table using the names array. The main bit of code I am having a problem with is when searching the yesno table as you can see in this code:
var goals = new Array();
//for loop to be used later when expanding
//for(var i = 1; i <= 22; i++){
var params = {
TableName: 'yesno',
FilterExpression: 'name = :value',
ExpressionAttributeValues: {':value': {"S": names[2]}}
};
dynamodb.scan(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
var temp = jsonToString(data.Items[0].goals);
goals[1] = temp;
}
callback(goals[1]);
});
//}
I know for sure there is nothing wrong with the implementation but here it is just in case it is helpful:
const handlers = {
'LaunchRequest': function () {
this.response.speak('welcome to magic answers. ask me a yes or no question.').listen('try again');
this.emit(':responseReady');
},
'MyIntent': function () {
var MyQuestion = this.event.request.intent.slots.MyQuestion.value;
console.log('MyQuestion : ' + MyQuestion);
const params2 = {
TableName: 'Fixtures',
FilterExpression: 'team1 = :value',
ExpressionAttributeValues: {':value': {"S": MyQuestion.toLowerCase()}}
};
//const params3 = {
// TableName: 'Fixtures',
// FilterExpression: 'team2 = :value',
// ExpressionAttributeValues: {':value': {"S": MyQuestion.toLowerCase()}}
//};
readDynamoItem(params2, myResult=>{
var say = MyQuestion;
say = myResult;
say = 'The top scorer for ' + MyQuestion + ' is ' + myResult;
this.response.speak(say).listen('try again');
this.emit(':responseReady');
});
},
'AMAZON.HelpIntent': function () {
this.response.speak('ask me a yes or no question.').listen('try again');
this.emit(':responseReady');
},
'AMAZON.CancelIntent': function () {
this.response.speak('Goodbye!');
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
this.response.speak('Goodbye!');
this.emit(':responseReady');
}
}
;

Request in NodeJS async waterfall return undefined

I'm pretty new to async on node js. I use the waterfall method while parsing a xml file like this:
$('situation').each( function(){
var situation = [];
$(this).find('situationRecord').each( function(i){
var record = this;
async.waterfall([
function (callback){
var filter = {
startLocationCode: $(record).find('alertCMethod2SecondaryPointLocation').find('specificLocation').text(),
endLocationCode: $(record).find('alertCMethod2PrimaryPointLocation').find('specificLocation').text(),
overallStartTime: $(record).find('overallStartTime').text(),
overallEndTime: $(record).find('overallEndTime').text()
}
callback(null, filter, record);
},
function (filter, record, callback){
var timestamp = new Date().toDateInputValue();
var startDbResponse = 0;
var endDbResponse = 0;
if((filter.startLocationCode != '') && new Date(timestamp) >= new Date(filter.overallStartTime) && new Date(timestamp) <= new Date(filter.overallEndTime) ){
startDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode);
endDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.endLocationCode);
}
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
callback(null, filter, record, startDbResponse, endDbResponse);
},
function (filter, record, startDbResponse, endDbResponse, callback){
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
var situationRecord = createSituationRecord($, record, filter.startLocationCode, filter.endLocationCode, startDbResponse, endDbResponse);
console.log(situationRecord);
},
function (situationRecord, callback){
situation[i] = { situationRecord };
}
],
function(err, results){
console.error("There was an error by filtering the xml file");
console.error(err);
});
})
if(situation.length > 0){ //if situation is not empty
locations.push(situation);
}
})
console.log(locations);
}
In this part of the waterfall I make a request to my database with locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode); but startDbResponse and endDbResponse is undefined :
....
function (filter, record, callback){
var timestamp = new Date().toDateInputValue();
var startDbResponse = 0;
var endDbResponse = 0;
if((filter.startLocationCode != '') && new Date(timestamp) >= new Date(filter.overallStartTime) && new Date(timestamp) <= new Date(filter.overallEndTime) ){
startDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.startLocationCode);
endDbResponse = locationCodeToGeodataRequst.geodataByLocationcode(filter.endLocationCode);
}
console.log("startDbResponse: ", startDbResponse);
console.log("endDbResponse: ", endDbResponse);
callback(null, filter, record, startDbResponse, endDbResponse);
},
....
The request by it self works because a console.log in the request module show the correct data. So I don't understand why its undefined.
This is the request module:
exports.geodataByLocationcode = function geodataByLocationcode(locationcode){
let sql = "SELECT * FROM tmc WHERE LOCATION_CODE = " + locationcode;
let query = db.query(sql, (err, result) =>{
if(err == null){
//console.log(result);
return result;
}else{
console.log("Error by getting item from db: " + err);
throw err;
}
});
}
This is a snipped of the console.log:
....
startDbResponse: undefined
endDbResponse: undefined
startDbResponse: undefined
endDbResponse: undefined
startDbResponse: 0
endDbResponse: 0
startDbResponse: 0
endDbResponse: 0
[]
//here comes the output of the requests as json objects
....
move the console log to the last function of async. As Manjeet pointed out async takes time and console prints early.
function (situationRecord, callback){
situation[i] = { situationRecord };
if(situation.length > 0){ //if situation is not empty
locations.push(situation);
}
})
console.log(locations);
}
}

How to use global error handling code in node.js for entire api call

I have a api call which has more than one functions. Instead of applying error-handling for each and every method, is it possible to use global error handling code that send the error to UI developers.
The code is given below:
app.post('/billing/pricingdetails', function (req, res) {
console.log('pricing api called');
var workload = req.body;
var resourcelevelPricing = {};
var response = {};
var workloadinfo = {
workloadId: workload.workloadId,
ownerId: workload.ownerId,
uniqueName: workload.uniqueName,
name: workload.name
}
var pricing = {}
var allresourceIdentifiers;
if (workload.elements && workload.elements.length > 0) {
var elementlevelpricingSummary = {};
var elementArray = [];
var allresourceIdentifierArray = [];
var elementinfo = {};
var metadataModified = {};
var elementsParam = workload.elements;
// handle configurable resource
var configurableElementarray = [];
// create array of all the elements in workloadjson - to be used for resourcelevel (instance/image), charamountunitlevel, resourcetypelevel pricing detail
for (var index in elementsParam) {
// if condition skips the uri of configurable resources - handle configurable resource
if(!elementsParam[index].parameters.ResourceParameters)
{
allresourceIdentifierArray.push(elementsParam[index].uri);
if (elementsParam[index].parameters.imageUri) {
allresourceIdentifierArray.push(elementsParam[index].parameters.imageUri);
}
}
}
var allresourceIdentifiers = allresourceIdentifierArray.join(',');
// call the functionalities that gives the each level of pricing detail synchronously to construct the workload json
async.series([
function (callback) {
getpricingSummary(elementsParam, function (err, workloadinfo) {
if(err){
}
else
{
callback(null, workloadinfo);
}
});
},
function (callback) {
getPricingforResourceIdentifiers(allresourceIdentifiers, function (err, pricingDetail) {
pricing.resourceLevel = pricingDetail;
callback(null, pricingDetail);
});
},
function (callback) {
getchargeamountunitlevelPricing(allresourceIdentifiers, function (err, pricingDetail) {
//merge configurable resource with concrete resource pricing details - handle configurable resource
if(configurableElementarray.length > 0)
{
var concatednatedArray = pricingDetail.concat(configurableElementarray);
var finalResult = [];
var i = concatednatedArray.reduce(function (result, o) {
var key = o.chargeAmountUnit + o.currencyCode;
if (!(key in result)) {
result.arr.push(result[key] = o);
finalResult.push(result);
}
else {
result[key].chargeAmount += Number(o.chargeAmount);
}
return result;
}, { arr: [] }).arr;
pricing.chargeamountunitLevel = i;
trace.info(i);
}
else
{
pricing.chargeamountunitLevel = pricingDetail;
}
callback(null, pricingDetail);
});
},
function (callback) {
getresourcetypelevelPricing(allresourceIdentifiers, function (err, pricingDetail) {
if(configurableElementarray.length > 0)
{
var concatednatedArray = pricingDetail.concat(configurableElementarray);
var i = concatednatedArray.reduce(function (result, o) {
var key = o.chargeAmountUnit + o.currencyCode + o.Name;
if (!(key in result)) {
result.arr.push(result[key] = o);
}
else {
result[key].chargeAmount += o.chargeAmount;
}
return result;
}, { arr: [] }).arr;
pricing.resourcetypeLevel = i;
trace.info(i);
}
else
{
pricing.resourcetypeLevel = pricingDetail;
}
callback(null, pricingDetail);
});
}
],
function (err, result) {
workloadinfo.pricing = pricing;
res.send(workloadinfo);
});
// get element level pricing summary for each elements (vm/vs) in the array within workload json - the output to be appended within metadata of workload json
function getpricingSummary(elementsParam, callback) {
async.forEachSeries(elementsParam, createResponse, function (err,result) {
return callback(null, result);
});
};
// this method called by async.forEachSeries passing each elements (vm/vs) of workload
function createResponse(elements, callback) {
var resourceIdentifierArray = [];
elementinfo = elements;
resourceIdentifierArray.push(elements.uri);
if (elements.parameters.imageUri) {
resourceIdentifierArray.push(elements.parameters.imageUri);
}
// build string of resourceIdentifier (instance/image) for input element
var resourceIdentifiers = resourceIdentifierArray.join(',');
console.log(resourceIdentifiers);
if(elements.parameters.ResourceParameters)
{
trace.info('1');
trace.info(elements.parameters.ResourceParameters);
var configJson = JSON.parse(elements.parameters.ResourceParameters);
trace.info(Number(configJson.cpuCount));
metadataModified = elements.metadata;
// TODO : Remove this hard-coding
elementlevelpricingSummary.Name = 'Hardware';
if(configJson.totalUnitPrice)
{
var chargeAmount = configJson.totalUnitPrice;
elementlevelpricingSummary.chargeAmount = Math.round(chargeAmount * 100)/100;
}
if(configJson.ChargeAmountUnit)
{
var chargeAmountUnit = configJson.ChargeAmountUnit;
elementlevelpricingSummary.chargeAmountUnit = configJson.ChargeAmountUnit;
}
if(configJson.CurrencyCode)
{
var currencyCode = configJson.CurrencyCode;
elementlevelpricingSummary.currencyCode = configJson.CurrencyCode;
}
metadataModified.pricingSummary = elementlevelpricingSummary;
configurableElementarray.push(elementlevelpricingSummary);
// delete original metadata from workload json (to be replaced by metadata containing pricing summary)
delete elementinfo.metadata;
elementinfo.metadata = metadataModified;
elementArray.push(elementinfo);
// global workloadinfo variable is appended with array of elements with its pricing summary within metadata of respective elements
workloadinfo.elements = elementArray;
return callback();
}
else
{
// Get element level pricing summary
mysql.elementlevelpricing(resourceIdentifiers, conn, function (result) {
elementlevelpricingSummary = result;
metadataModified = elements.metadata;
metadataModified.pricingSummary = elementlevelpricingSummary;
// delete original metadata from workload json (to be replaced by metadata containing pricing summary)
delete elementinfo.metadata;
elementinfo.metadata = metadataModified;
elementArray.push(elementinfo);
// global workloadinfo variable is appended with array of elements with its pricing summary within metadata of respective elements
workloadinfo.elements = elementArray;
return callback(null,workloadinfo);
});
}
};
function getPricingforResourceIdentifiers(resourceIdentifiers, callback) {
mysql.pricingDetail(resourceIdentifiers, conn, function (result) {
return callback(null, result);
});
};
function getchargeamountunitlevelPricing(resourceIdentifiers, callback) {
mysql.chargeamountunitlevelPricing(resourceIdentifiers, conn, function (result) {
return callback(null, result);
});
};
function getresourcetypelevelPricing(resourceIdentifiers, callback) {
mysql.resourcetypelevelPricing(resourceIdentifiers, conn, function (result) {
return callback(null, result);
});
};
};
});
With Express, you can install an error handler which will be called when an error occurs in any of your routes:
// somewhere at the end of your middleware/route chain
app.use(function(err, req, res, next) {
res.send(500, err.message); // or whatever you want to send back
});
It would still be best to rethrow any errors that occur in your code:
if (err) throw err;
Also, since you're using async, you can always propagate errors back to it:
if (err) return callback(err);
And handle the errors in the final callback.

Categories

Resources