0

I want to pass into Seq([644511,340755]) an response from async function getProjects.

So I tried

...
var ids = pivotal.getProjects(function (err, data) {
  var ids = data.project.map(function(x) { return parseInt(x.id); });
  console.log("IDS_i: ".red + ids);
});
console.log("IDS_e: ".red + ids);

Seq(ids)
  .parEach(function(project_id) {
....

Logs:

IDS_e: undefined
GET /stories 200 34ms
GET /favicon.ico 404 2ms
IDS_i: 644511,340755

I am wondering maybe I should put this into Seq:

Seq()
   .seq(function() {
      pivotal.getProjects(function (err, data) {
        data.project.map(function(x) { return parseInt(x.id); });
      });
    }

but how to return ids as array in that case?

tomekfranek
  • 6,852
  • 8
  • 45
  • 80

1 Answers1

1

getProjects is also async. A basic rule: You can't return any values from an async function. You have to do all processing in the callback function. Execution will continue before your arrays have been aggregated. So your seq approach is what you need:

Seq()
    .seq(function() {
        pivotal.getProjects(this);
    })
    .flatten()
    .seqEach(function(project) {
        var projectId = project.id;
        myService.someOtherAsyncAction(projectId, this);
    });

node-seq will take care of passing the result of the callback to the next seq step by passing this as the callback function to your async function. This is how flow and results are passed to the next step. flatten will make sure each project is available as individual elements on the stack so you can do seqEach in the next step.

NilsH
  • 13,705
  • 4
  • 41
  • 59
  • Ok, I understand but have one problem with ``projects.project.map(function(x) { return parseInt(x.id); });`` how to pass it to new step(``.parEach``) as array. I have to put this into the new function?? – tomekfranek Mar 29 '13 at 21:14
  • You could try `seqEach` instead of `seq` as the second step. You might have to `flatten` the array though so each `project` is considered an element on the stack. I'll update the answer with some pseudo code. – NilsH Mar 29 '13 at 21:30
  • Thanks, one thing looks like flatten() is not what I need. I can't use seqEach on flatten() because ``this`` is ``[object Object]`` I have to someway set ``this`` as ``this.project`` and then I will get ``object Object],[object Object]`` – tomekfranek Mar 29 '13 at 21:49
  • I'm not sure I fully understand, but you could try with `flatten(false)`. You can consult the documentation for [node-seq](https://github.com/substack/node-seq) for more details. – NilsH Mar 29 '13 at 23:26