Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ForEach不';t更新主阵列_Javascript_Node.js - Fatal编程技术网

Javascript ForEach不';t更新主阵列

Javascript ForEach不';t更新主阵列,javascript,node.js,Javascript,Node.js,我试图向数组的每个项添加一些附加值。我有一个包含对象的数组,它们有:x,y和z字段。然后,我想根据http.get调用的响应向数组中的每个对象添加其他项 主数组是:posts 见下面的代码: router.get('/api/posts', function(req, res){ postModel.find({}) .limit(10) .exec(function(err, posts) { var options = {

我试图向数组的每个项添加一些附加值。我有一个包含对象的数组,它们有:x,y和z字段。然后,我想根据http.get调用的响应向数组中的每个对象添加其他项

主数组是:posts

见下面的代码:

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');
            }
        });
});
在执行post.profilePic=parsedBody.user.profilePic时,profilePic变量存在,但当我通过res.json从节点获得响应时,附加值不存在

我错过了什么?我一直使用这种方法来处理我的角度前端,没有任何问题


感谢

节点根据回调进行工作。您在forEach循环中没有完成回调,并且正在向用户提供响应。这就是问题所在

为我可以建议的解决方案编写代码

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){
                var EventEmitter = require('events');
                var HttpEvent = new EventEmitter();
                let counts = 0;
                let length = posts.length;

                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);
                            posts.fullname = parsedBody.user.fullname;
                            posts.profilePic = parsedBody.user.profilePic;
                            HttpEvent.emit('done');
                        });
                    });      
                });

                HttpEvent.on('done',()=>{
                    counts += 1;
                    if(counts == length){
                         res.json({
                            posts       :   posts
                        });
                    }
                })

            } else {
                res.send('Post does not exist');
            }
        });
});
你做的另一件错事是

 post.fullname = parsedBody.user.fullname;
 post.profilePic = parsedBody.user.profilePic;
应该是

 posts.fullname = parsedBody.user.fullname;
 posts.profilePic = parsedBody.user.profilePic;

节点根据回调进行工作。您在forEach循环中没有完成回调,并且正在向用户提供响应。这就是问题所在

为我可以建议的解决方案编写代码

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){
                var EventEmitter = require('events');
                var HttpEvent = new EventEmitter();
                let counts = 0;
                let length = posts.length;

                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);
                            posts.fullname = parsedBody.user.fullname;
                            posts.profilePic = parsedBody.user.profilePic;
                            HttpEvent.emit('done');
                        });
                    });      
                });

                HttpEvent.on('done',()=>{
                    counts += 1;
                    if(counts == length){
                         res.json({
                            posts       :   posts
                        });
                    }
                })

            } else {
                res.send('Post does not exist');
            }
        });
});
你做的另一件错事是

 post.fullname = parsedBody.user.fullname;
 post.profilePic = parsedBody.user.profilePic;
应该是

 posts.fullname = parsedBody.user.fullname;
 posts.profilePic = parsedBody.user.profilePic;

这是一个非常常见的问题,您将异步代码视为同步代码
http.get
不会立即完成,也不会阻止代码继续,因此在请求完成之前会调用
res.json
。有很多方法可以解决这个问题,我会发布我最喜欢的-


这是一个非常常见的问题,您将异步代码视为同步代码
http.get
不会立即完成,也不会阻止代码继续,因此在请求完成之前会调用
res.json
。有很多方法可以解决这个问题,我会发布我最喜欢的-


尝试一件事:将
post
分配给某个变量
var temp=post
。然后将
fullname
profilePic
添加到该变量
temp.fullname=parsedBody.user.fullname
post.profilePic=parsedBody.user.profilePic
。现在返回
temp
,而不是
posts
。感谢您的评论。这种方法会奏效,但肯定有一种更自然的方法,对吗?我必须将大部分数据放在数组中,这将导致巨大的内存开销(实际数据量很大)。尝试一件事:将
post
分配给某个变量
var temp=post
。然后将
fullname
profilePic
添加到该变量
temp.fullname=parsedBody.user.fullname
post.profilePic=parsedBody.user.profilePic
。现在返回
temp
,而不是
posts
。感谢您的评论。这种方法会奏效,但肯定有一种更自然的方法,对吗?我将不得不推到阵列,其中大部分数据已经存在,这将导致巨大的内存开销(真正的数据是巨大的)。感谢您的评论。我只是试了一下,但没用。返回的数据仍然没有值。同样对于post.fullname=parsedBody.user.fullname;-它以这种方式命名,因为它是循环的一部分。我在论坛上发帖子,谢谢你的评论。我只是试了一下,但没用。返回的数据仍然没有值。同样对于post.fullname=parsedBody.user.fullname;-它以这种方式命名,因为它是循环的一部分。我又一次通过了forEachAh的职位!我讨厌我总是被它们缠住。谢谢你,罗布。这对我来说就像一个符咒!啊,又来了一个!我讨厌我总是被它们缠住。谢谢你,罗布。这对我来说就像一个符咒!