0

Say you have a promise chain like this:

asyncFunction()
.then((value) => {
    resolve(value)
})
.then((value) => {
    resolve(value)
})
.then((value) => {
    resolve(value)
})
.catch((error) => {
    reject(error)
})

If an error is thrown during one of those function calls, does that error automatically propagate all the way down to the catch at the end of the chain? Say the error is thrown at the beginning, during asyncFunction(), what are the exact mechanics of how it propagates? Is the error passed to the handler of each then? Or does each then look for a second handler, not see one, and so pass the error to the next then?

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
RNdev
  • 457
  • 1
  • 10

1 Answers1

1

Yes, it will get propagated down until it hits the first catch. All then clauses should be skipped.

I noticed the use of resolve() and reject() avoid this, there's no need for the Promise constructor pattern in case like this.

Evert
  • 75,014
  • 17
  • 95
  • 156
  • 2 questions: 1) when you say it gets propagated to the next catch, you mean if an error is thrown, it just skips the `then`s? And 2) I don't understand what you mean about resolve and reject. Could you elaborate? – RNdev May 01 '20 at 16:13
  • 1) Yes. 2) The resolve() and reject() functions suggest that you wrapped this in `new Promise()`. You don't need to do this. Just return the chain from the function instead of a 'new promise'. – Evert May 01 '20 at 16:38
  • Let me make sure I understand: the fact that resolve and reject are available implies the whole code block is wrapped in `new Promise()`, right? So the alternative is to not wrap it in `new Promise()`, and instead to do `return value` instead of `resolve value`? – RNdev May 01 '20 at 20:29
  • Yes, that was my guess! And yes the alternative is to use `return asyncFunction.then(...etc...)` – Evert May 01 '20 at 21:45
  • What I meant was, where I now have `resolve(value)` etc, use `return(value)`? – RNdev May 02 '20 at 00:41
  • Your code does not really make sense, because you don't want to call resolve() multiple times. But yes, the thing you want to return from main function should be returned in the last step. – Evert May 02 '20 at 01:23