Friday, 7 April 2017

ForEach doesn't update main array

I am trying to add some additional values to each item of an array. So I have an array with objects and they have: x, y and z fields. I then want to add additional items to each object in the array based on a http.get call's response.

Main array is: posts

See code below:

router.get('/api/posts', function(req, res){

    postModel.find({})
        .limit(10)
        .exec(function(err, posts) {
            var options = {
                host: 'localhost',
                port: 3000,
                path: '/user?id=12345678',
                method: 'GET'
            };
            if(posts){
                posts.forEach(function(post) {

                    var req = http.get(options, function(res) {
                        var bodyChunks = [];
                        res.on('data', function(chunk) {
                            bodyChunks.push(chunk);
                        }).on('end', function() {
                            var body = Buffer.concat(bodyChunks);
                            var parsedBody = JSON.parse(body);
                            post.fullname = parsedBody.user.fullname;
                            post.profilePic = parsedBody.user.profilePic;
                        });
                    });      
                });
            res.json({
                posts       :   posts
            });
            } else {
                res.send('Post does not exist');
            }
        });
});

At the time of the post.profilePic = parsedBody.user.profilePic - the profilePic variable is there but when I get a response from node via res.json, the additional values are not.

What am I missing here? I use this approach with my Angular frontend all the time without an issue.

Thanks



via Shayan Khan

No comments:

Post a Comment