I am working on node.js library called node-geocoder. I am trying to create a function which will return only country name. My code is given below:
const NodeGeocoder = require('node-geocoder');
var NodeGeocoderOptions = {
provider: 'google',
// Optional depending on the providers
httpAdapter: 'https',
apiKey: gmapkey,
formatter: null
};
var geocoder = NodeGeocoder(NodeGeocoderOptions);
// get country
function getCountry(lat, long){
country_name = "";
geocoder.reverse({lat:lat, lon:long}, function(err, res) {
// country_name = res[0].country;
country_name += res[0].country;
});
console.log("Country Name is " + country_name);
return country_name;
}
I am getting the response.how can i return country name.
Thanks in advance.
Related
I want to return data to function that calls a function with firebase code, because of the asynchronous and nested structure of firebase queries it is not able to return values, I intend to use this logic to set tool tips in chart.js
Here is my code:
window.onload = function() {
get_data();
}
function get_data() {
var data = get_val();
console.log("...." + data);
}
function get_val() {
var label = "10/2/2017";
var Name = localStorage.getItem("VName");
console.log("Name:::" + Name);
var at_val;
var dbref = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EInfo/");
dbref.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
var Nameval = data.Name;
if (Nameval == Name) {
console.log("Success");
Ikey = childsnapshot.key();
console.log("Key:::" + Ikey);
var dxRef = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EApraise/" + Ikey);
dxRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
console.log(data);
if (label == data.Dateval) {
console.log("-------> bingo");
at_val = data.Attitude;
console.log("got value:" + at_val);
}
});
}).then(function() {
console.log("In then:" + at_val);
return at_val;
});
}
})
})
}
Data is loaded from the Firebase Database asynchronously. You cannot return a value now that hasn't been loaded yet. And until the async and await keywords are commonplace, you cannot make JavaScript wait for the async value.
The closest you can get today is to return a promise from get_val(). Then your calling code will be:
get_val().then(function(data) {
console.log("...." + data);
});
To do this you'll have to implement get_val() as:
function get_val() {
var label = "10/2/2017";
var Name = localStorage.getItem("VName") || "delta";
console.log("Name:::" + Name);
var at_val;
var dbref = firebase.database().ref("EmployeeDB/EInfo/").orderByChild("Name").equalTo(Name);
return dbref.once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
var Nameval = data.Name;
Ikey = childsnapshot.key;
var dxRef = firebase.database().ref("EmployeeDB/EApraise/" + Ikey).orderByChild("Dateval").equalTo(label);
promises.push(
dxRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
at_val = data.Attitude;
});
}).then(function() {
console.log("In then:" + at_val);
return at_val;
})
);
})
return Promise.all(promises);
})
}
I made a few changes to get_val():
it uses the new 3.x versions of the Firebase SDK. The solution could also work with 2.x, I just didn't feel like setting up a jsbin for that.
it populates a list of promises, one for each of the EApraise records
it returns a promise that resolves when all the EApraise records are loaded.
it uses Firebase queries to find the correct record. This removes the need for checking the values in the then() callbacks. But more importantly it ensures that only the necessary data is downloaded.
To make that last point true, you need to add a few index definitions to the rules in your Firebase Database console:
{
"rules": {
"EmployeeDB": {
"EInfo": {
".indexOn": "Name"
}
"EApraise": {
"$eid": {
".indexOn": "Dateval"
}
}
}
}
}
Here a jsbin with the working code: http://jsbin.com/jawamilawo/edit?js,console
I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?
Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
I have a utility function which pass parameters 'name page callback' to the function. Why not work as i tried so many times?
PLUS: seems 'query.tag_id = name' work for me but why query[name] = name did not work so that i can pass whatever name i like;That's, i want to pass the variable /name/ as the property name so that i can use whatever name i like. For example, i can find posts by user_id when i pass user_id variable as the name value. Also i can find posts by its tag_id when i pass tag_id variable as the name value so it's much more flexible than when i use 'query.user_id = name' to do it ,where the name can only be user_id variable or value
NO LIBRARY USED EXCEPT EXPRESS AND NODEJS WITH CONNECT-FLESH, MONGOOSE ETC.
// post_proxy/post.js
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTen: (name,page,callback)=>{
var query = {};
//name = query;
if(name){
query[name] = name;
console.log('query[name] is'+ Object.keys(query));
}
Post.count(query, ( err, count)=>{
if (err) {
return callback(err);
}else{
console.log( `Number of posts: ${count} . query is ${query}` );
Post.find(query).skip((page-1)*10).limit(10).sort({created_at: -1}).exec((err,posts)=>{
if (err) {
return callback(err);
}
console.log('Posts inthe getTen function is: '+posts);
const modifiedPosts = posts.map(post=>{
return post.processPost(post);
});
console.log('modifiedPosts: '+modifiedPosts);
callback(null, modifiedPosts, count);//provide the params(caluated values),and what to do? you need to figure it out yourself
});
}
});
}
// controller/post.js:
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTagsPost: (req,res)=>{
const tag_id = req.params.tag_id;
const page = req.query.p ? parseInt(req.query.p) : 1;
//let loginedUser;
console.log('entering into the tagpost');
postProxy.getTen(tag_id, page, (err, posts, count)=> {
if (err) {
console.log('some error with getting the 10 posts:'+ err);
//next(err);
posts = [];
}
// if(req.user){
// loginedUser = req.user.processUser(req.user);
// }
//userProxy.getUserById(user_id, theuser=>{
console.log('tag posts for'+ tag_id +posts);
res.render('post/tagPosts', {
title: 'specific tag page',
user: req.user ? req.user.processUser(req.user) : req.user,
//postUser: req.user ? (req.user._id == user_id ? loginedUser : theuser) : theuser,
posts: posts,
page: page,
isFirstPage: (page - 1) == 0,
isLastPage: ((page - 1) * 10 + posts.length) == count,
messages: {
error: req.flash('error'),
success: req.flash('success'),
info: req.flash('info'),
}, // get the user out of session and pass to template
});
});
},
...
}
//route:
router.get('/tag/:tag_id', post.getTagsPost);
UPDATE:
Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}
UPDATE: Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}
I'm currently working on this function, and the return value returns with undefined. I'm not sure if it is my lack of understanding how javascript operates, or it requires some tricky voodoo to make my code work.
var fs = require('fs');
var _ = require('underscore');
function eventValue(current, choice) {
var output = [];
if (current != null) {
var json;
fs.readFile('./json.json', 'utf8', function(err, data) {
if (err) {
throw err
}
json = JSON.parse(data);
// filter by ID
var filtered = _.filter(json, {
'ID': current
});
//console.log(filtered);
// Get ID of Object
var ID = _.pluck(filtered, 'ID');
// Get Next value of object
var NEXT = _.pluck(filtered, 'next');
// get nested 'choice's 'next' value
var collect = _.pluck(_.filter(
_.flatten(
_.pluck(filtered, 'choice')), {
'choice': choice
}), 'next');
var stringID = String(ID);
var stringNext = String(NEXT + collect);
output = [stringID, stringNext];
return output;
})
} else console.log("[[error]] please populate eventValue()");
};
var a = eventValue("001001A01B01");
console.log(a);
You are trying to use value returned from asynchronous function callback which you can not.
Refer: How to get returned value by function with callback inside
I would like to pass the current context or an attribute to functions in async.waterfall. How to:
pass this
an attribute (here options object)
This is what I already have:
var _authenticate = function (cbAsync) {
var licenseId = options.licenseId; //options is undefined
};
module.exports = new Command('createOrga')
.description('creates an organization')
.option('-f, --file <file>', 'the structure file including full path')
.action(function (options) {
options.confirm = options.confirm || true; // No confirmation needed!
options.organizationUUID = (uuid.v4()).toUpperCase();
options.licenseId = (uuid.v4()).toUpperCase();
//How to pass options object to _authenticate function????
async.waterfall([ _authenticate ], function(err) {
if ( err ) {
console.warn('Error in creating new organization: ',err);
}
else {
console.info('Successfully created new organization: ' + organizationUUID);
}
});
}
}
You could use Function.prototype.bind() to pass variables.
async.waterfall([ _authenticate.bind(undefined, options)], function(err) {
//your code
});
Because the bound variables are pass first, your callback then has to look like this:
var _authenticate = function (options, cbAsync) {
var licenseId = options.licenseId; //options is undefined
};