How to pass into Seq reponse of function?

How to pass into Seq reponse of function?

Problem

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?

Problem courtesy of: tomekfranek

Solution

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.

Solution courtesy of: NilsH

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *