1

我想渲染 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]
4

2 回答 2

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将并行执行函数,并且在并行seq执行的所有回调完成后执行以下操作。node-seq将每次并行执行的结果放入下面的参数数组中seq,因此有点神秘Hash.map(this.args)

于 2013-03-29T19:00:09.513 回答
0

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

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);
    }
  });
});
于 2013-03-29T18:53:30.800 回答