0

Is is possible to use the value returned from a previous then method in a then chain to the catch method if any of the next then methods fail?

So for instance if we have:

fetch('https://example.com')
  .then( res => doSomething(res) )
  .then( res2 => doSomethingElse(res2) )
  .then( res3 => console.log(res3) )
  .catch( res2 => console.log(res2) )

So say the second then fails (doSomethingElse), can I pass the value of the last successful then to the catch block? (in this case the first one would be the last one to pass)

Byrd
  • 402
  • 4
  • 5
  • Use nesting to handle errors on only those promises you want to use, so that `res2` is still in scope: `fetch(…).then(doSomething).then(res2 => doSomethingElse.then(res3 => console.log(res3)).catch(err => console.log(res2, err))).catch(err2 => …)` – Bergi Oct 20 '17 at 22:55
  • Ahh good idea, Thank you for that and sorry about the duplicate question. – Byrd Oct 21 '17 at 19:14
  • Actually I'm not quite sure whether it's a good duplicate, as the control flow is actually quite different in case of an error - only the [nesting approach](https://stackoverflow.com/a/28250687/1048572) fits here. Maybe I should reopen and post a proper answer. – Bergi Oct 21 '17 at 20:03

1 Answers1

0

Why don't you use a variable for this?

var lastResult = null    
fetch('https://example.com')
   .then( res => lastResult = res; doSomething(res) )
   .then( res2 => lastResult = res2; doSomethingElse(res2) )
   .then( res3 => lastResult = res3; console.log(res3) )
   .catch( err => process(lastResult); console.log(err) )
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
  • Yea I guess you could do it this way, I was looking for a way that fits the flow a little more, so kinda like what @Bergi commented as well as the question he linked as mine was a duplicate. Thank you for your answer though! – Byrd Oct 21 '17 at 19:16