简体   繁体   English

Express JS在渲染视图之前处理数据

[英]Express js manipulate data before render view

I am new using nodejs and express and was wondering what is the best practice to manipulate data before render a view. 我是使用Node.js和Express的新手,我想知道在渲染视图之前处理数据的最佳实践是什么。 Currently i want to set some variables based on the retrieved data to render the view. 目前,我想基于检索到的数据设置一些变量以呈现视图。 So far this is what i have, but I am not sure if this is the best practice or if there is any better way to do it. 到目前为止,这就是我所拥有的,但是我不确定这是否是最佳做法,或者是否有更好的方法来做到这一点。

var request = require('request');

module.exports = function(req, res, next) {
  request.get('http://nout.nout-app.com/getAccessVIPForUserId/' + req.params.id, function(err, resp, body) {
    var bodyResp = JSON.parse(body);

    bodyResp.data.forEach(function(el, index, array){
      if(el.access_status === '1') {
        el.status = 'success';
      } else {
        el.status = 'warning';
      }

      if(el.access_friend === '1') {
        el.access_friend = 'yes';
      } else {
        el.access_friend = 'no';
      }
    });

    console.log(bodyResp.data);
      if(err || (typeof bodyResp.data === 'undefined' || bodyResp.data === null)) {
        res.render('error', {
          message: bodyResp.reason ? bodyResp.reason : 'Something went wrong',
          error: {
            status: 500
          }
        });
      } else {
        res.render('profile', {
            intern: true,
            user: req.user,
            invitations: bodyResp.data
        });
      }
  });
};

I appreciate if you guys could give me guide in this and also suggest some good material to improve. 如果您能在此方面给我提供指导,并提出一些改进的好材料,我将不胜感激。 Regards. 问候。

Yes, .forEach is blocking (synchronous), but it is extremely fast . 是的, .forEach正在阻止(同步),但是它非常快 In general you don't need to worry about for basic data manipulation like that. 通常,您无需担心像这样的基本数据操作。 Remember - async doesn't make something take less time, it just gives other things the ability to keep happening in the mean time. 请记住-异步不会使事情花费更少的时间,它只是使其他事物能够在此期间不断发生。

If you really want to make your loop async, have a look at the async module. 如果您真的想使循环异步,请查看异步模块。 async.each is an async version of .forEach async.each是一个异步版本.forEach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM