Promise Gotchas
Avoiding common mistakes
Promises don’t work like other values
You cannot print their value like most values:
Promises don’t warn you when making a mistake
Well, a likely mistake.
For a variety of reasons, it was decided by TC39 that .then
and .catch
may be passed null. For example, .then(null, null)
is valid and the required behavior is to skip that ‘step’ in the chain.
The unfortunate consequence of this is it’s very easy to screw things up.
By Example
Let’s look at a mini challenge: which of the following option(s) will console.log
42?
The Answer
The answer is #2, #3 & #4.
Why? Let’s look at the types of what was passed to .then()
:
Still wondering how that 4th Option works?
It’s effectively running like this: