2013-03-29 43 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

相關問題