2013-03-29 45 views
0

我想使用pivotal-node模块为node.js返回已完成关键故事的数组。在node.js中如何用json对象数组发送响应?

app.get('/delivered_stories', function(request, response) {    
    pivotal.useToken("my_token"); 
    pivotal.getProjects(function (err, data) { 
    var project_ids = data.project.map(function(x) { return parseInt(x.id); }); 
    console.log('Retrived project ids: '.blue + project_ids); 

    project_ids.forEach(function(id) { 
     pivotal.getStories(id, { filter: "state:finished" }, function(err, story) { 
     response.send(story); 
     }); 
    }); 
    response.end(); // End the JSON array and response. 
    }); 
}); 

我在做什么错了?以及如何解决它?我得到一个错误:

http.js:708 
    throw new Error('Can\'t set headers after they are sent.'); 
     ^
Error: Can't set headers after they are sent. 

整个代码:https://gist.github.com/regedarek/30b2f35e92a7f98f4e20

回答

2

pivotal.getStories()异步

其回调(因此response.send())将后运行一段时间您的代码(包括response.end()

事实上,你不应该叫response.end()在所有的休息; response.send()是为你做的。

您也不能多次拨打response.send();您需要将所有结果合并到一个数组中并发送。
这并不简单;考虑使用async.js或承诺。

+0

那么我如何存储''project_ids''并将其传递给getStories? – tomekfranek

+0

@regedarek查看用于协调异步任务的异步库。 https://github.com/caolan/async – UpTheCreek

+0

哎呀刚才看到答案提到 - 仍然值得重申;) – UpTheCreek

相关问题