0

Using the Q library with node.js,

I'd like to create a simple flow with 5-6 steps for each request and I'm trying to decide between two options of passing a request id to each step of the flow.

function(){

   var reqId = generateId();

   // opt a
   firstStep(reqId)
   .then(secondStep);

}

function firstStep(reqId){

    var resultOfFirstStep = doSomething();

    promise.resolve({

       reqId: reqId,
       result: resultOfFirstStep

    }); 

}

function secondStep(data){

    var reqId = data.reqId
    ...

}

// opt b

 function(){

   var reqId = generateId();

   firstStep(reqId)
   .then(secondStep.bind(this,reqId));

 }

function firstStep(reqId){

    var resultOfFirstStep = doSomething();

    promise.resolve(result); 

}

function secondStep(reqId,result){

    ...

}

The first option doesn't seem very elegant, whereas I'm not sure whether it is advisable to create a copy of each function due to the usage of bind().

Or maybe I'm missing a better way of achieving this?

Thanks.

Shahar
  • 478
  • 5
  • 17
  • `firstStep` and `secondStep` seems to be closures over `reqId` already, so why are you passing it explicitly at all? Regardless, see the duplicate for various ways of passing multiple values through a chain. – Bergi Apr 10 '16 at 13:16
  • My mistake in showing they were closures. that's not the case (I've edited the q.) In the duplicate question, most of the answers refer to using .spread() or a similar way, but in my case it is mandatory that each step runs after the previous. There is a link there in one of the comments that suggests a way of doing what I need but it's not decisive. I think this question is a bit more specific and would help others so I'm not sure about it being marked as duplicated. I still believe that using bind is the cleaner way. Just not sure if I'm hitting performance or exposing myself to leaks. – Shahar Apr 10 '16 at 14:06
  • 1
    Using `bind` is totally fine. It's effectively just a way to flatten [the closure solution](http://stackoverflow.com/a/28250687/1048572). Btw, all the solutions offered in the duplicate do run the steps sequentially, you can use any of them. – Bergi Apr 10 '16 at 14:18

0 Answers0