To demonstrate that reject does not halt processing I wrote this trivial example.
function wait(seconds) { return new Promise((resolve, reject) => { if (seconds == null || seconds == 5) { console.log('Before reject'); reject('Please supply number not equal to 5'); console.log('After reject'); } setTimeout(() => { resolve('Done'); }, seconds * 1000); }); }
It's a function that returns a Promise.
If the seconds specified is 5, then the expected behavior is to reject and not wait.
Any other value, I expect it to wait the specified time.
This is how I call my function:
wait(seconds) .then(() => { console.log('Successfully completed test'); }) .catch((error) => { console.error('Error in test', error); });
Here is my output when running the function:
Test 1
With a value of seconds = 7
The wait function behaves as expected. It waits 7 seconds and resolves.
Successfully completed test
Test 2
With a value of seconds = 5
The wait function does not behave as expected. It waited 5 seconds!
Before reject After reject Error in test Please supply number not equal to 5
I didn't expect the "After reject" and I didn't expect it to wait the 5 seconds.
To correct this add a return statement after the reject.
function wait(seconds) { return new Promise((resolve, reject) => { if (seconds == null || seconds == 5) { reject('Please supply number not equal to 5'); return; // Do not continue } setTimeout(() => { resolve('Done'); }, seconds * 1000); }); }
Now re-executing test 2 above produces:
Error in test Please supply number not equal to 5
And there was no wait which is the expected behavior.
Read more about Promises here: https://www.freecodecamp.org/news/javascript-es6-promises-for-beginners-resolve-reject-and-chaining-explained/
Top comments (2)
An alternative to using the return is to use an else.
In my opinion the
else
approach is a bit messy vs earlyreturn
. And early return is a nice way to act as a guard statement that doesn't nest the code an extra layer like theelse
statement does.You could (and probably should) just
return
the reject statement like this: