Reputation: 573
I am new using nodejs and express and was wondering what is the best practice to manipulate data before render a view. 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.
Upvotes: 1
Views: 829
Reputation: 8523
Yes, .forEach
is blocking (synchronous), but it is extremely fast. 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
Upvotes: 1