I’m a bit confused about how Promises work in JavaScript ES6. I thought that when a Promise resolves or rejects, it would stop running right away. But I’ve noticed that the code inside the Promise keeps going even after resolve() or reject() is called.
I was expecting resolve and reject to work kind of like return statements, stopping everything in their tracks. But that’s not what’s happening.
Here’s a quick example to show what I mean:
function test() {
return new Promise((resolve, reject) => {
resolve('Done');
console.log('This still shows up!');
});
}
test().then(() => console.log('Promise resolved'));
When you run this, you’ll see both console logs. Can anyone explain why the code keeps running after resolve() is called? Is there a reason for this behavior that I’m missing?
yeah, i noticed that too. it’s kinda weird but apparently it’s how promises are designed. they don’t stop right away when you resolve or reject. the code keeps going until it’s done. if you want it to stop, you gotta add a return after resolve() or reject(). took me a while to figure that out lol
This behavior often catches developers off guard, but it’s actually by design. When you call resolve() or reject(), it doesn’t immediately halt execution like a return statement would. Instead, it marks the Promise as settled and schedules the resolution to occur on the next tick of the event loop.
The rationale behind this is to maintain consistent asynchronous behavior. It allows you to set up multiple resolution paths within a single Promise executor function, which can be useful in complex scenarios. However, it’s generally good practice to return after calling resolve() or reject() to prevent unintended side effects.
If you want to ensure no code runs after resolution, you can simply add a return statement right after your resolve() or reject() call. This approach is cleaner and prevents any confusion about what might execute afterwards.
I’ve run into this issue before, and it can be pretty confusing at first. The thing to remember is that Promises don’t work like traditional synchronous code. When you call resolve() or reject(), it’s more like setting a flag than immediately stopping execution.
In my experience, it’s best to think of the Promise as a wrapper around your asynchronous operation. The resolve() or reject() calls are just signaling the outcome, but they don’t interrupt the flow inside the Promise.
If you want to ensure nothing runs after resolving, you can use an early return:
return new Promise((resolve) => {
resolve('Done');
return; // This prevents further execution
console.log('This won't run');
});
This pattern has saved me a lot of headaches in larger, more complex Promise chains. Just remember: resolve doesn’t mean stop, it means ‘we’re done, but I’ll let you finish up’.