JavaScript中Promise不同调用方式的执行差异及异常问题咨询
Understanding Your Promise Execution Behavior
Great question! Let's break down exactly what's happening in both of your Promise scenarios—this gets to the core of how Promises handle callbacks, state changes, and error propagation.
First Scenario: p.then(doSomething1); p.then(doSomething2); p.catch(doSomething3)
When you attach multiple .then() calls directly to the original Promise p, here's the breakdown:
- Each
.then()registers an independent callback that listens forp's state change. - Assuming
somePromiseresolves successfully (since you see the sequence1->2), all callbacks attached directly topwill execute in the order they were registered. - First
doSomething1runs (outputting1), thendoSomething2runs (outputting2). - The
.catch(doSomething3)only triggers ifpitself is rejected. Sincepresolved without errors, this callback never executes.
That's why you see the sequence 1->2.
Second Scenario: p.then(doSomething1).then(() => { throw some error }); p.then(doSomething2); p.catch(doSomething3)
This scenario hinges on a key Promise behavior: every .then() or .catch() call returns a brand new Promise instance. Let's break it down step by step:
p.then(doSomething1)creates a new Promise (let's call itp1). SincedoSomething1runs successfully (as in the first scenario),p1resolves.p1.then(() => { throw new Error() })creates another new Promise (p2). When the callback throws an error,p2transitions to a rejected state.- Critical note:
p2is a completely separate Promise from the originalp. The error inp2does not affectp's state—premains resolved!
Why you see 1->3 and an unhandled rejection warning
Let's unpack these two outcomes:
- Unhandled rejection warning: The rejected Promise
p2has no.catch()callback attached to it. JavaScript engines flag this because it's an uncaught error in a Promise chain that no code is handling. - Why
doSomething3runs: If your code actually has the.catch(doSomething3)attached to the chained Promise (instead of the originalp, likep.then(doSomething1).then(() => { throw error }).catch(doSomething3)), thendoSomething3would run to handlep2's error. If it's attached top, it shouldn't run—unlesspitself was rejected elsewhere (which contradicts your first scenario's success).
The core lessons here are:
- Chained Promises are independent of the original Promise. Errors in a chain only affect the new Promises created by
.then()/.catch()calls. - Callbacks attached directly to the original Promise only react to the original Promise's state changes, not changes in chained Promises.
内容的提问来源于stack exchange,提问作者moon.pike
相关产品推荐
相关产品推荐

