Reputation: 287
I try every possible solution that is available in SO. like using global
or using bind
but can not access the global variable. here is my code i am trying to generate sitemap
in nodejs
here is my .js
file.
module.exports = function (portal) {
var mongoose = require('mongoose');
var News = mongoose.model('News');
var urls ="";
var gensitemap = function(){
urls = "abc";
console.log(urls);// print abc as expected
News.find().exec(function (err, news) {
news.forEach(function (t) {
urls += "<url><loc>"+cdn_url+"/news"+t.slug+"</loc>"+"</url>";
});
});
console.log(urls);// print still abc as not expected it should be change
}
var allUsers = portal.setupContext({});
app.get('/gensitemap',allUsers ,gensitemap);
};
here you can see i use url
variable befor and after News.find()
method.but instead of change the url its is printing same output.
Any idea i already try global
or async.parallel({})
but same issue in News.find()
node js treat that variable as different.
Any help ?
UPDATE :
After reading the comments and some of the mention question i try this
Events.find().exec(function (err1, events) {
events.forEach(function (t1) {
url += "<url><loc>"+cdn_url+"/event"+t1.slug+"</loc>"+changefreq+priority+"</url>";
});
News.find().exec(function (err2, news) {
news.forEach(function (t2) {
url += "<url><loc>"+cdn_url+"/news"+t2.slug+"</loc>"+changefreq+priority+"</url>";
});
var static_urls = ['about-us','categories','overview','media','contact-us','login','register','pages/en/faq'];
for(var i = 0 ;i < static_urls.length;i++){
url += "<url><loc>"+"http://192.168.10.38:3000/"+static_urls[i]+"</loc>"+"<changefreq>weekly</changefreq>"+"<priority>1</priority>"+"</url>";
}
console.log(url);
//this url(variable) print only the changes i made in above for loop.. :-(
});
});
I also notice after waiting some time i am able to see the change but they are not in same order.
Upvotes: 0
Views: 911
Reputation: 2661
module.exports = function (portal) {
var mongoose = require('mongoose');
var News = mongoose.model('News');
var urls ="";
var gensitemap = function(){
urls = "abc";
console.log(urls);// print abc as expected
News.find().exec(function (err, news) {//this block of code gets executed after the News.find().exec() function return . Anything you want to do after the exec function call get a response you have to do it here. inside this call back function.
news.forEach(function (t) {
urls += "<url><loc>"+cdn_url+"/news"+t.slug+"</loc>"+"</url>";
});
//if you log the url here you should find ur desired value
console.log(urls);
});
//This is getting called before your News.find().exec() function returns any value.
console.log(urls);// print still abc as not expected it should be change
}
var allUsers = portal.setupContext({});
app.get('/gensitemap',allUsers ,gensitemap);
};
Upvotes: 1