I want to return array of finished pivotal stories using pivotal-node module for node.js.

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.
  });
});

What I am doing wrong? And how to fix it? I get an error:

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

Whole code: https://gist.github.com/regedarek/30b2f35e92a7f98f4e20

share|improve this question

1 Answer

pivotal.getStories() is asynchronous.

Its callback (and therefore response.send()) will run some time after the rest of your code (including response.end())

In fact, you shouldn't be calling response.end() at all; response.send() does that for you.

You also cannot call response.send() more than once; you need to combine all of the results into a single array and send that.
This is not simple to do; consider using async.js or promises.

share|improve this answer
So how I can store project_ids and pass it to getStories ? – regedarek 30 mins ago
@regedarek Take a look at the async library for co-ordinating async tasks. github.com/caolan/async – UpTheCreek 25 mins ago
Oops just saw that the answer mentioned that - still it's worth reiterating ;) – UpTheCreek 24 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.