Javascript 为什么console.log()将变量放置在呈现视图的函数中时会重复打印?

Javascript 为什么console.log()将变量放置在呈现视图的函数中时会重复打印?,javascript,node.js,express,handlebars.js,express-handlebars,Javascript,Node.js,Express,Handlebars.js,Express Handlebars,我有一个简单的全局变量,它在我的app.js文件中保存一个字符串: global.MyActivity = "peanutbutterjellytime" 我有另一个文件index.js,它是一个路由器/控制器。在此文件中,我执行以下操作: var router = require('express').Router(); console.log(global.MyActivity); // this prints the variable once to the console. Great

我有一个简单的全局变量,它在我的
app.js
文件中保存一个字符串:

global.MyActivity = "peanutbutterjellytime"
我有另一个文件
index.js
,它是一个路由器/控制器。在此文件中,我执行以下操作:

var router = require('express').Router();
console.log(global.MyActivity); // this prints the variable once to the console. Great!

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints the variable in duplicate
    res.render('index', {pagetitle: 'Activity Page'}); // i think this is causing the problem. if i remove it it works fine
});

module.exports = router;
我总是注释掉
console.log(global.MyActivity)
router.get()方法之外,因此我知道它不会因为任何附加而进行重复打印

我不明白为什么在渲染视图时,控制台会打印变量两次,而如果我删除渲染代码,它会正确地打印,并且只打印一次。所以这很好:

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints once
    console.log("I am sync"); // this prints once
});

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints twice!
    console.log("I am async"); // this prints twice!
    res.render('index', {pagetitle: 'Activity Page'}); 
});
如果我想像
res.render('index',{pagetitle:'Activity Page',Activity:global.MyActivity})那样将
global.MyActivity
发送到我的视图,这会导致一个问题,因为它是重复的。我的视图引擎是express Handlebar,它只是用于express的handlebar.js

更新/修复1(福禄克,我不明白它为什么会起作用) 为了好玩,我加入了一个回调函数。这解决了控制台日志重复的问题,但视图从不呈现

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints once now! why?

    res.render('index', {pagetitle: 'Activity Page'}, function(){ }); // this never renders 

});

从某个浏览器调用路由时是否检查日志?还是你在使用邮递员/卷发之类的工具request@AbhishekAnand更新了我的问题。问题不在router.get()方法中,而是异步函数。如果我删除async,那么它只打印一次您的Node js版本是什么@volumeone@EmilHotkowski它是最新的v12.13.0。我还更新了我的问题,因为引起问题的不是异步,而是
res.render('index',{pagetitle:'Activity Page'})零件。如果我删除它,那么它只向控制台打印一次,这是正确的。如果不使用回调,您可以检查问题是否仍然存在。render.res.render(“索引”);