I could not return the value from the function, I have no problem with my sql it works fine, I just can't return the result value and pass it to res variable.
io.on('connection', function (socket) {
socket.on('getdetails', function (data) {
var res = getdatatodb(data.id);
console.log("result",res);
});
});
});
function getdatatodb(id){
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
var options = {sql: ".....",nestTables: true };
connection.query(options,function(err, results) {
if(err){
console.log(err);
}
return results;
});
});
}
Thank you in advance.
Related
I am looking to assign as an object a Fetch API promise from a local GeoJSON file.
Here is the code
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites
}).addTo(map);
});
};
I tried the call back method, as advised here
Saving fetched JSON into variable
(EDIT) New code, but there is still a missing formal parameter
function getData("data/sites.geojson", cb) {
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function (feature, layer) {
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
.then(function(result) {
cb(result);
});
});
};
getData("data/sites.geojson", function (data) {
return console.log({data});
});
Most probably just incorrect syntax of your callback function:
// Use either arrow function
getData("data/sites.geojson", (data) => {
return console.log({data});
});
// or standard function
getData("data/sites.geojson", function (data) {
return console.log({data});
});
I found the way to work this out by adding within the fetch function, what I originally wanted to do on the map.
This was to add a L.controlLayer using the geojson as overlay.
This is the code that made it work:
let sites = getData()
.then((function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function LayerControl(feature, layer) {
var popupText = "<b>" + feature.properties.nombre + "<br>";
layer.bindPopup(popupText);
category = feature.properties.tipo;
// Initialize the category array if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = L.layerGroup().addTo(map);
layersControl.addOverlay(categories[category], category);
}
categories[category].addLayer(layer);
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
}));
Actually it comes from one of your answer on another post ghybs.
I have the following code to return all the keys in the level DB in Node.js app, this is a method in a ES6 class:
class LevelDB {
constructor() {
this.db = level(chainDB);
}
getAllItems() {
let self = this;
return new Promise(function(resolve, reject){
self.db.createKeyStream()
.on('data', function (data) {
resolve(data);
})
.on('error', function (err) {
reject(err)
});
}
}
The database is created successfully.
What I'm notice is that the on data or on error is never fired? Im new using level so any help will be appreciate.
This solve the issue;
I just realize that I need to wait for the Stream close:
class LevelDB {
constructor() {
this.db = level(chainDB);
}
getAllItems() {
let self = this;
let dataArray = [];
return new Promise(function(resolve, reject){
self.db.createKeyStream()
.on('data', function (data) {
dataArray.push(data);
})
.on('error', function (err) {
reject(err)
})
.on('close', function () {
resolve(dataArray);
})
}
}
I Need Access to file name in my request body because i want store in my db but i dont know handle that , this is my code :
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
** Im want pass name variable**
callback(null, name);
}
});
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
***upload(req, res, function (data) {
I need access to file name here because i want store in my db***
console.log(data);
res.end("File is uploaded");
});
});
Im try this way but not working :
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
callback(name, name);
}
});
you can access to path from req.file.path like this :
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
upload(req, res, function (data) {
console.log(req.file.path);
res.end("File is uploaded");
});
});
I have this code here but I cannot figure out why the second FS.readfile() executes last. Basically I want to:
readFile(passwd)
.then(console(textpasswd)
.then(readFile(hosts).
.then(console(texthosts);
But what happens is the readFile(hosts) executes last in the chain. I sense something is wrong with my deferring, but what?
Here is the code
module.paths.push('/usr/local/lib/node_modules');
var Q = require('q');
var FS=require('fs');
var deferred = Q.defer();
var p=deferred.promise;
FS.readFile("/etc/passwd", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
p.then(function (text) {
console.log(text);
}).then(FS.readFile("/etc/hosts", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
})
).then(function (text) {
console.log(text);
});
The deferred must obtain a new promise to continue the chain correctly. Also notice the first (function())() must be executed to return a promise although you don't need to do it this way. So here is my solution. (I cleaned it up a little):
module.paths.push('/usr/local/lib/node_modules');
var Q = require('q');
var FS = require('fs');
(function () {
var deferred = Q.defer();
FS.readFile("/etc/passwd", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
})
return deferred.promise;
})().then(function (text) {
console.log(text);
}).then(function () {
var deferred = Q.defer();
FS.readFile("/etc/hosts", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
})
return deferred.promise;
}).then(function (text) {
console.log(text);
}).then(function () {
console.log('The End');
});
I got problem while I move into https://github.com/DaftMonk/generator-angular-fullstack.
Before my project was working. Here is code for frontend and backend part related to comment.
I am getting all time error 404. I don't know why I cannot find following path.
POST http://localhost:9000/api/providers/554a1dba53d9ca8c2a2a31ff/posts/554b1726f1116e00256e3d82/comments 404 (Not Found)
I am struggling couple of days to discover which part of my code have problem but I couldn't realize that.
server side
in comment.controller
// Creates a new comment in the DB.
exports.create = function(req, res) {
console.log('i ma inside api');
Post.findById(req.originalUrl.split('/')[3], function (err, post) { //here can not find post at all.
if (err) {
return handleError(res, err);
}
if (!post) {
return res.status(404).send('Post not found');
}
Comment.create(req.body, function (err, comment) {
if (err) {
return handleError(res, err);
}
post.comments.push(comment.id);
post.save(function (err) {
if (err) return handleError(res, err);
return res.status(201).json(comment);
});
});
});
};
route.js
app.use('/api/providers/:providerId/posts/:postId/comments', require('./api/provider/post/comment'));
index.js
var controller = require('./comment.controller.js');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
router.put('/:id/upvote', controller.upvote);
in client side:
factory:
//create new comment for post
ob.createComment = function(providerId, postId,comment) {
console.log('i am inside factory');
return $http.post('/api/providers/'+ providerId + '/posts/' + postId + '/comments' ,comment, {
headers: {Authorization: 'Bearer '+Auth.getToken()}
}).success(function(data){
_.forEach(ob.provider.posts,function(value,index){
if(value._id === post._id){
ob.posts[index].comments.push(data);
}
})
ob.current.comments.push(data)
// ob.provider1._id.posts.push(data);
});
};
in my controller
$scope.addComment = function(){
// if(!$scope.title || $scope.title === '') { return; }
if(!$scope.body || $scope.body === '') { return; }
console.log('$stateParams',$stateParams);
providers.createComment($stateParams.providerId, $stateParams.postId,{
//title: $scope.title,
body: $scope.body
});
$scope.body = '';
$scope.title = '';
};
This is my model in whole the project.