how do I access a named parameter in a function? [duplicate] - javascript

This question already has answers here:
Using multiple parameters in URL in express
(3 answers)
Closed 8 years ago.
I'm developing a REST web service using Node JS to work in conjunction with Backbone JS.
One of the REST methods is GET /users/id/:id, where :id is the id number of a user. This method will return the details of the user from a database.
What I don't understand is how can I pass the :id parameter from the url to the response handler.
I've defined the response handler in app.js like this:
app.get('users/id/:id',user.fetch(db));
and this is the user.fetch function
exports.fetch = function(db){
return function(req,res){
var id = ;//how do I get the Id from the request?
console.log("id: "+id);
if(id !== null){
peopleDb = db.get('people');
peopleDb.find({"_id":id},function(e,docs){
if(e){
console.log(e);
}else
{
res.setHeader('Content-Type','application/json');
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.writeHead(200);
res.end(JSON.stringify(docs));
}
});
}
}
}

return function(req,res)
{
var id = req.params.id;
console.log("id: "+id);
// ...
this should works as expected. You can read more here

Related

Can't store API data in js global variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Using async/await with a forEach loop
(33 answers)
Closed 1 year ago.
I am trying to build a simple crypto portfolio in nodejs by fetching prices from coingecko API. I set up a simple mongodb with all assets and I am parsing through the db and fetching each price. The fetch works as I can console.log the results however I cannot seem to be able to store the prices in a variable that I can call outside the fetch function. Thus, I cannot pass the prices to my ejs file. I am quite new to js (coming from python), and it seems that I am missing someting on how to handle api results, here is my code:
app.get('/dashboard', (req, res) => {
Holdings.find ((err, allHoldings) => {
if (err) {
res.type('html').status(500);
res.send('Error: ' + err);
}
else if (allHoldings.length == 0) {
res.type('html').status(200);
res.send('You have no holdings');
}
else {
var priceList = {};
allHoldings.forEach(async coin => {
coin = coin.asset;
const uri = 'https://api.coingecko.com/api/v3/simple/price?ids=' + coin + '&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&//include_24hr_change=false&//include_last_updated_at=false';
const fetch_price = await fetch(uri);
const json = await fetch_price.json()
const price = json[coin]['usd'];
priceList[coin] = price;
priceList.save;
console.log(priceList);
return priceList;
});
console.log(priceList);
res.render('dashboard', { holdings : allHoldings})
}
});
});
As you can see I set a priceList object before performing the API fetch and then I try to push the pair {coin : price} to that object. The first console.log works fine, however the second one only logs an empty object.
Any idea ?
Thanks

Getting data from nested .then function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Long story short. I'm trying to learn javascript. And i've been googling for about 4 hours straight right now. And i cant find the answer to my current problem, so i'm assuming i'm looking at this the wrong way.
I'm trying to create a slackbot. The bot is connected, and can look for messages so that part is working.
I've (tried to)create(ed) a function that gets the userID of everynew message based on the name i set in. In my mind this function returns the userID, and that i can later down the code check if userID is in message.text, if it is do something.
I'm assuming it has something to do with that .then function. Can i even return data from that .then function? or can u just use that data inside of that function.
I have several return functions as i was trying to just return it from wherever u could.
function getuserid(botname){
var id = ''
var getbotid = bot.getUsers();
getbotid.then(function(value){
for(var i=0;i<value.members.length;i++){
if(value.members[i].name == botname){
id = value.members[i].id
console.log(id);//this logs what i want.
return id
}
} return id
})
return id
}
var botid = getuserid('jokester');
console.log(botid);
I'm not sure but in my experience, if you return getbotid() then actually you return a promise and you can use it .
function getuserid(botname){
var id = ''
//************Here I return getbotid
return bot.getUsers().then(function(value){
for(var i=0;i<value.members.length;i++){
if(value.members[i].name == botname){
id = value.members[i].id
console.log(id);//this logs what i want.
return id
}
} return id
})
return id
}
//Now you can use it
getuserid('jokester').then(id => console.log(botid));

Bringing one value outside of an err response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I am trying to get one of the events outside and print it. Of course the 'answer' variable scope is only inside.
As you can see, this one gets a list of all the events stored on a specific calendar. I am able to access specific events from the array. However. I don't know how to get that one value out of this.
I am not that familiar with coding, help appreciated.
//my question is just above the last line.
let google = require('googleapis');
let privatekey = mypk.json;
// configure a JWT auth client
let jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/calendar']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
return;
} else {
console.log("Successfully connected!");
}
});
let calendar = google.calendar('v3');
calendar.events.list({
auth: jwtClient,
calendarId: 'xxxxx#group.calendar.google.com'
}
, function (err, response, cb) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var events = response.items;
var singleEvent = events[0].summary;
return;
/* if (events.length == 0) {
console.log('No events found.');
} else {
console.log('Event from Google Calendar:');
for (let event of response.items) {
console.log('Event name: %s, Creator name: %s, Create date: %s', event.summary, event.creator.displayName, event.start.date);
}
}*/
}
);
//this is what I need to get, one event but the variable has no scope here.
console.log ('this is the ' + singleEvent);
Declare the variable singleEvent just after calendar
Like this:
let calendar = google.calendar('v3');
let singleEvent;
And inside the callback do the following:
singleEvent = events[0].summary;
Note: Understanding scopes in Javascript is probably the most important thing you need to learn. This article will probably help you a lot:
https://scotch.io/tutorials/understanding-scope-in-javascript

JavaScript setting public variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a question regarding setting 'public' variable in JavaScript. Here is my code:
var storeKey;
firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
var storeData = snapshot.val();
if (storeData){
console.log('exists');
}else{
storeKey = firebase.database().ref('stores').push({
storeName : "store1",
storeAddress : "Blk 167"
}).getKey();
//console.log("STORE " + storeKey);
}
});
console.log("STORE " + storeKey);
I am checking if the address exists before adding new record into Firebase. However, if I put the console.log at the last line, I get undefined. It only returns a value if I print it out inside the else statement.
I wanted to separate the storeKey out before I need that data in other places and I don't want my code to be nested inside the else statement. Any idea how to achieve this?
Your function accepts a callback, the console.log is called before the callback, that's why its undefined One way to "solve" it is using promises. e.g.
const deferred = q.defer();
firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
var storeData = snapshot.val();
if (storeData){
console.log('exists');
}else{
storeKey = firebase.database().ref('stores').push({
storeName : "store1",
storeAddress : "Blk 167"
}).getKey();
deferred.resolve(storeKey);
}
});
deferred.then(console.log)

Mongoose does not send the updated result [duplicate]

This question already has answers here:
Mongoose findByIdAndUpdate not returning correct model
(2 answers)
Closed 7 years ago.
Im trying to add an item to an array and get back the updated model.
I PUT my request like so:
addCarToDriver(CarToAdd) {
const self = this;
request
.put('api/drivers/' + this.state.race._id)
.send({
car: CarToAdd})
.end(function(err, res) {
console.log(res.body);
self.setState({race: res.body});
});
}
It hits the server here :
MyRace.findByIdAndUpdate(
req.params.myrace_id,
{ $push: { 'cars': req.body.car } },
function(er, model) {
if (er) {
console.log(err);
return res.send(err);
}
console.log(model);
return res.json(model);
});
Now in the request callback I would expect the new updated model to get logged, i.e with the new Car. It does not. The "old" version gets logged. However, if i refresh the page the model gets updated with the new car.
Of course I need to setState directly in the callback. Any tips on how to do this?
Mongoose 4 has changed .findAndUpdate behavior to return the old document by default, and if you want the new updated one you need to pass {new:true}, because that was the actual behavior in MongoDB
You can patch the Query to set options.new=true to have the old way back:
var __setOptions = mongoose.Query.prototype.setOptions;
mongoose.Query.prototype.setOptions = function(options, overwrite) {
__setOptions.apply(this, arguments);
this.options['new'] = true;
return this;
};

Categories