nodejs中的全局变量

时间:2017-11-20 11:10:19

标签: node.js variables global

我尝试在SO中提供的所有可能的解决方案。比如使用global或使用bind但无法访问全局变量。这是我的代码我想在sitemap中生成nodejs这里是我的.js文件。

    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);
  };

在这里你可以看到我使用url变量befor和News.find()方法。但是不是更改url,而是打印相同的输出。

我知道我已尝试globalasync.parallel({}),但News.find()节点js中的同一问题将该变量视为不同。

有任何帮助吗?

更新:

在阅读评论和一些提及问题后,我试试这个

    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.. :-(
                });
        });

我也注意到在等了一段时间后我能看到变化,但它们的顺序不一样。

1 个答案:

答案 0 :(得分:1)

    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);
  };