全局变量在交换机内部不起作用-javascript

时间:2018-09-27 07:21:51

标签: javascript variables switch-statement global-variables

 let visitor;
 const role = req.user.profile;

 // role will be either Admin or Manager

 switch (role) {
   case 'Admin':
     if (req.body.verificationMode === 'online') {
       visitor = {
         name: req.body.name,
         mode: 'online',
       };
     } else {
       visitor = {
         name: req.body.name,
         mode: 'offline'
       };
     }
     break;


   case 'Manager':
     Staff.findOne({
       where: {
         loginId: req.user.id,
       },
     }).then((staffData) => {
       if (req.body.verificationMode === 'online') {
         visitor = {
           name: req.body.name,
           mode: 'online',
         };
       } else {
         visitor = {
           name: req.body.name,
           mode: 'offline',
         };
       }
     });
     break;

 }
 console.log('visitor >>> >> >> >> >>> >>>> >>>> >>>> >>> >>>> >>>', visitor);

如果我以 Admin 角色登录,则访问者的控制台具有正确的数据,但是如果以 Manager 角色登录,访问者的控制台将变为 undefined

为什么会这样?我正在使用ES6,所以我不使用var。

1 个答案:

答案 0 :(得分:1)

您有一个异步代码,以防Manager在console.log之后执行。那就是为什么在这种情况下未定义访问者的原因。

使用它。

 let visitor;
 const role = req.user.profile;
 let callback = function(){
     console.log('visitor >>> >> >> >> >>> >>>> >>>> >>>> >>> >>>> >>>', visitor); 
 }
 // role will be either Admin or Manager



 switch (role) {
   case 'Admin':
     if (req.body.verificationMode === 'online') {
       visitor = {
         name: req.body.name,
         mode: 'online',
       };
     } else {
       visitor = {
         name: req.body.name,
         mode: 'offline'
       };
     }
     callback();
     break;


   case 'Manager':
     Staff.findOne({
       where: {
         loginId: req.user.id,
       },
     }).then((staffData) => {
       if (req.body.verificationMode === 'online') {
         visitor = {
           name: req.body.name,
           mode: 'online',
         };
       } else {
         visitor = {
           name: req.body.name,
           mode: 'offline',
         };
       }
       callback();
     });
     break;

 }

console.log移动到一个函数,该函数在visitor值初始化之后被调用。