0

I have a chain of promises some of which pass arguments down the chain, like this:

stepOne(argument).catch(errorHandler)
  .then(stepTwo).catch(errorHandler)
  .then(stepThree).catch(errorHandler)
  .then(stepFour).catch(errorHandler)
...

function stepTwo(data)
{
  // stuff
  return promise
    .then(function(data){ return Promise.resolve({arg: 'a', arg2: 'b'); }) //pass this to step three, step three does the same to four
    .catch(function(err){ return Promise.reject(err); });    
}

I'd like to be able to combine that with another argument from the calling function at the chain level, like so:

stepOne(argument).catch(errorHandler)
  .then(stepTwo).catch(errorHandler)
  .then(stepThree(dataFromTwo, extraArg)).catch(errorHandler)
  .then(stepFour(dataFromThree, extraArg, moreArg)).catch(errorHandler)
...

The goal is to reuse code and avoid duplication. However anytime I try to do that I end up with undefined values or overwriting one or the other set of parameters, how do I do this? Ideally I'd like to not have to make a superfluous promise just to merge parameters.

blackbird
  • 1,129
  • 1
  • 23
  • 48
  • If you're dependent on data from `stepTwo`, let `stepTwo` return that data. If `StepThree` is dependent on something in current closure, write a function that returns a `StepThree` based on data in the current closure – JanS Mar 28 '18 at 15:00
  • 2
    You need to pass a function: `.then(dataFromTwo => stepThree(dataFromTwo, extraArg))` – Bergi Mar 28 '18 at 15:02
  • @JanS so there's basically no better way than making an intermediate promise just to combine arguments? – blackbird Mar 28 '18 at 15:03
  • @Bergi thanks! I'll try that, can you explain why this works? sorry I'm new to Promise – blackbird Mar 28 '18 at 15:03
  • 1
    Btw, drop the pointless `.catch(function(err){ return Promise.reject(err); });` (especially if you're keen on avoiding unnecessary intermediate promises!) – Bergi Mar 28 '18 at 15:06
  • @Bergi brilliant, thanks so much. Care to make it an A so I'll accept it? – blackbird Mar 28 '18 at 15:10

0 Answers0