Return value to variable from function - javascript

I am looking to return a value to a varible when I call the function in nodejs.
The output I am looking for is "Calling From Glasgow to Euston"
The output I am getting is "Calling From undefined to undefined"
Code is the following.
function trainstation(stx, callBack) {
MongoClient.connect(ttdb, function(err, db) {
if (err) throw err;
var dbo = db.db("ttdb");
var collection = dbo.collection("tlc");
var find = collection.find( { "Stanox" : stx } );
find.toArray(function(err, result) {
if (err) throw err;
db.close();
return callBack(result);
});
});
};
function gettrain(){
var ts1 = trainstation(9531, function(x){
return x[0]['Station Name'];
});
var ts2 = trainstation(31033, function(x){
return x[0]['Station Name'];
});
console.log("Calling From", ts1, "to", ts2);
};
gettrain();
Thanks :)

I don't use the MongoDB package and I don't have MongoDB up & running right now to test this, so I've written this code purely based on a quick read of the reference documentation. Perhaps you can test this and we'll fix any minor issues. Copy this code to a new source file and test it.
What I've done is to take advantage of the MongoDB package's promise features. You can see that the code is more linear and simpler to follow.
const MongoClient = require('mongodb').MongoClient;
const ttdb = 'mongodb://localhost:27017'; // or your DB URL
const trainstation = async (Stanox) => {
const client = MongoClient(ttdb);
await client.connect();
const dbo = client.db("ttdb");
const collection = dbo.collection("tlc");
const result = await collection.find({Stanox}).toArray();
client.close();
return result;
};
const gettrain = async () => {
const ts1 = await trainstation(9531);
const ts2 = await trainstation(31033);
const sn1 = ts1[0]['Station Name'];
const sn2 = ts2[0]['Station Name'];
console.log("Calling From", sn1, "to", sn2);
};
gettrain();

Related

Why mongoose is not awaiting for await new MODEL.save()

I have 2 servers and one of these is work fine, but second (modified variant of first) is not
`This is not works:
router.post("/", async (req, res, next) => {
const newBriefAppeal = await new BriefAppeal(req.body);
let appealId;
let target;
let goals;
let brand;
let ***;
try {
const savedBriefAppeal = await newBriefAppeal.save(function (err, appeal) {
appealId = appeal.id;
target = appeal.step01target;
goals = appeal.step02goals;
brand = appeal.step03brand;
*** = appeal.***
});
res.status(200).json(savedBriefAppeal);
} catch (err) {
res.status(500).json(err);
}
});
`
and i got error
node:events:491
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of undefined (reading 'id')
`but this variant in my similar project works fine:
router.post("/", async (req, res, next) => {
const newAppeal = await new Appeal(req.body);
let appealId;
let name;
let email;
let phone;
let subject;
let message;
let attachments = [];
try {
const savedAppeal = await newAppeal.save(function (err, appeal) {
appealId = appeal.id;
name = appeal.name;
email = appeal.email;
phone = appeal.phone;
subject = appeal.subject;
message = appeal.text;
attachments = appeal.appealAttach.map((attachment) => ({
filename: attachment,
path: "./uploads/media/mailAttachments/" + attachment,
}));
});
res.status(200).json(savedAppeal);
} catch (err) {
res.status(500).json(err);
}
});
Where's i'm wrong and why my appeal is undefined ?
Because you're passing in a callback. As it says in the documentation, save only returns a promise when you don't pass in a callback:
Returns:
...Returns undefined if used with callback or a Promise otherwise.
Either use the old-style callback signature or use the promise feature.

Why is Data not being passed through my Node REST API?

I have the following code.
routes/index.js:
const express = require('express');
const router = express.Router();
const weeklyReportsController = require('../controllers/weeklyReportsController');
router.get('/weekly_reports', weeklyReportsController);
module.exports = router;
controllers/weeklyReportsController.js:
const weeklyReportsService = require('../services/weeklyReportsService');
const weeklyReportsController = async (req, res) => {
try {
const data = await weeklyReportsService;
res.json({data})
console.log('Weekly reports controller - success');
} catch(err) {
console.log(err);
}
};
module.exports = weeklyReportsController;
services/weeklyReportsService.js:
const Pool = require('pg').Pool
const pool = new Pool({connection data})
const weeklyReportsService = async () => {
const res = await pool.query('SELECT * FROM reports', (err, results) => {
if (err) {
throw err;
} else {
console.log('Weekly reports service - success.');
}
return res.status(200).json(results.rows);
});
};
module.exports = weeklyReportsService;
All I am returning by visiting localhost:8080/api/weekly_reports is an empty JSON object of {}. I tried adding some console.log() methods to my code to see what was triggering and what wasn't, and the log from my service is not being set off. I have spent a couple hours trying to dig through example codes, reading documentation, and honestly just looking blankly at my screen - I just can't figure out what I did wrong here.
Does anyone have a suggestion as to what I am doing wrong here?
Thank you all for your time and if there is anything I can add for clarity, please don't hesitate to ask and I will provide it.
Thank you for your help.
EDIT: The data is sitting in a Postgres database called reports with the table also called reports.
There are many things wrong with your approach
Here's how you can achieve what you're trying to do:
controllers/weeklyReportsController.js:
const weeklyReportsController = async (req, res) => {
try {
const data = await weeklyReportsService();
res.status(200).json({data})
console.log('Weekly reports controller - success');
} catch(err) {
console.log(err);
res.status(500).json({error: err.message})
}
};
module.exports = weeklyReportsController;
services/weeklyReportsService.js:
const Pool = require('pg').Pool
const pool = new Pool({connection data})
const weeklyReportsService = () => {
return new Promise((resolve,reject) => {
pool.query('SELECT * FROM reports', (err, results) => {
if (err) reject(err);
console.log('Weekly reports service - success.');
resolve(results.rows)
});
})
};
module.exports = weeklyReportsService;
some links to help you get started:
https://expressjs.com/en/api.html#res
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://stackoverflow.com/a/64052334/2703813
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

How to call a javascript function inside another function in node js

I have a file index.js as below. Where I am trying to call a async function getConn in other function createThumbnails. But I am getting the error as "failed to connect to DEDC: 1433 - self signed certificate" in the catch block.
const sharp = require('sharp');
const sql = require('mssql')
// CONNECTION CONFIGURATION OF BASE DB
async function getConn() {
try {
const config = {
user: 'sa_user',
password: '*******',
server: 'DEDC',
database: 'DEMO_BASE'
}
const pool = await new sql.ConnectionPool(config)
const req=await pool.connect()
const conn = await req.request()
return conn;
} catch (err) {
return err;
}
};
const createThumbnails = async() => {
try{
var conn = await getConn();
const query = `exec DBBASE.get_client_info`
var clientusers = await conn.query(query);
} catch (err) {
return err;
}
}
createThumbnails()
How do I exactly call the function getConn inside createThumbnails. Please help. Thanks in advance
It's because you are using variable with the same name as the function.
Try different name:
var conn = await getConn();
const query = `exec DBBASE.get_client_info`
var clientusers = await conn.query(query);
You encounter what called hoisting. Kyle Simpson has a great explaination on this topic
var getConn = await getConn();
which means getConn will be initialized first, before assignment, which equivalents to
var getConn // initialized
getConn = await getConn() // assignment
Then turned out that you got the error
Solution here is to store it in a different variable name, like
var conn = await getConn();
async function getConn() {
return {
query: async () => {
console.log("query called");
},
};
}
const createThumbnails = async () => {
try {
var conn = await getConn();
const query = `exec DBBASE.get_client_info`;
var clientusers = await conn.query(query);
} catch (err) {
console.log(err);
}
};
createThumbnails();
We need to use trustServerCertificate: true in DB configuration i.e in const config

Dynamically create async function (error)

I am trying to code asyncfunction but I get an error(await is only valid in async function), the question is: it's possible to do this?
const run_qry = require('./sequelize');
app.post('/resultdata', (req, res) => {
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
let test001 = new AsyncFunction('dat', `{
var mySet = new Set();
var arrObj = [];
// QUERY TO DATABASE
let queryDB = await run_qry.query('select * from public.list_users()');
// LOOP DATA
queryDB.forEach((element, index, array) => {
var row = [];
row.push({vareg: element.val, trans_id: element.id, til_scrip: 1});
row.push({vareg: element.val, trans_id: element.id, til_scrip: 1});
mySet.add(row);
});
// NEW ARRAY
for (let rs of mySet) {
const objReg = new Object();
for (let rs_child of rs) {
objReg["col" + rs_child.vareg] = rs_child.vareg;
objReg["col" + rs_child.vareg + "_type"] = rs_child.til_scrip;
};
arrObj.push(objReg);
};
//RETURNING NEW ARRAY OBJ
return arrObj;
};`);
test001(null).then(x => { res.send(x); });
});
i'm using nodejs and express, i would greatly appreciate any help or any option to do it.
ERROR:
SyntaxError: await is only valid in async function
at new Function (<anonymous>)
The await works only within in the async function. Change your arrow function to arrow async function.
change this line
app.post('/resultdata', (req, res) => {
to this
app.post('/resultdata', async (req, res) => {

How to use util.promisify to promisify a function in NodeJs?

I am trying to convert a Callback function into a Promise,
I'm using util.promisify for this and following is my working code vs the new non working one.
Working code, using Node Callback style -
let AWS = require(aws-sdk');
let moduleName = process.env.Module;
module.exports = {
getConstants
};
function getConstants (callback) {
let client = new AWS.SSM({
region: "us-east-1"
});
let smName = "/somePath";
let params = {
Names: [smName]
};
client.getParameters(params, function (err, data) {
if (err) {
console.log(err, err.stack);
callback(err, null);
}
else{
console.log(METHOD_TAG,'Parameter Store call successful!');
let constantVariables = data.Parameters[0].Value;
callback(null, constantVariables);
}
});
}
New Non working code -
let AWS = require('aws-sdk');
let util = require('util');
let moduleName = process.env.Module;
module.exports.getConstants = async () => {
let client = new AWS.SSM({
region: "us-east-1"
});
let smName = "/somePath";
let params = {
Names: [smName]
};
let parameterStore = util.promisify(client.getParameters).bind(client);
let response = await parameterStore.getParameters(params);
let constantVariables = response.Parameters[0].Value;
return constantVariables;
};
I am getting the following error -
TypeError: parameterStore.getParameters is not a function"
when trying to promisify the getParameters function of the AWS.SSM client.
What am I doing wrong, what should I change?
Reference -
https://medium.com/#suyashmohan/util-promisify-in-node-js-v8-d07ef4ea8c53
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParameters-property

Categories

Resources