简体   繁体   中英

How to pass into Seq reponse of function?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM