如何从forEach函数聚合json对象数组?

时间:2013-03-29 18:41:12

标签: javascript json node.js

我想渲染node.js中所有项目的故事数组。怎么做?

app.get('/stories', function(request, response) {
  var projects_ids = [1,2]; 
  project_ids.forEach(function(id) {
    pivotal.getStories(id, function(err, project_stories) {
      console.log("Stories: " + project_stories);

      return JSON.stringify(project_stories);
    });
  });
  response.send(array_of_stories);
});

在日志中我得到:

Stories: [object Object]
Stories: [object Object]

2 个答案:

答案 0 :(得分:1)

由于getStories是异步的(基于getStories的方法签名的假设),因此您当前的方法将无效。如果可以,我建议您在pivotal上创建一个可以获取多个项目ID的故事的方法,因此您的代码将显示为:

app.get('/stories', function(req, res) {
    var project_ids = [1, 2];
    pivotal.getStories(project_ids, function(err, project_stories) {
        res.send(project_stories);
    }
});

如果这不是一个选项,我建议您查看一个流程库,例如node-seq。然后你的代码可以读出这样的东西:

app.get('/stories', function(req, res) {
    var project_ids = [1, 2];
    Seq(project_ids)
        .parEach(function(project_id) {
            pivotal.getStories(project_id, this);
        })
        .seq(function() {
            var aggregatedStories = [];
            Hash.map(this.args, (function(arg) {
            // Each parSeq aparently results in an array of objects
                aggregatedStories.push(arg[0]);
            }));
            res.send(aggregatedStories);
        });
});

Hash.map函数来自名为hashish

的节点模块

编辑:为了详细说明,parEach将并行执行这些函数,并且在并行执行的所有回调完成后,将执行以下seqnode-seq将每个并行执行的结果放入以下seq的参数数组中,因此有点神秘Hash.map(this.args)

答案 1 :(得分:0)

您希望服务器发送project_stories个对象数组作为对请求的响应吗?我不确定你的return语句返回到哪里,所以省略我会尝试类似于下面的内容来发送一个对象数组作为对请求的响应。 编辑:正如其他人所指出的,.getStories是异步的。也许你可以试试,caolan's async module。像这样实现:

var async = require('async');
var array_of_stories = [];

var getStories = function(id, callback) {
  pivotal.getStories(id, function(err, project_stories) {
    array_of_stories.push(project_stories);
  });
}

app.get('/stories', function(request, response) {
  var projects_ids = [1,2];
  async.forEach(project_ids, getStories, function(error) {
    if(!error){
      response.send(array_of_stories);
    }
  });
});