How does JavaScript "take back" an uncaught Promise? - javascript

If I enter the following into the console, no error is reported to the console
let p = new Promise(function(resolve, reject) {
console.log('started')
reject('immediately reject')
})
console.log('do some other work')
p.catch(function(error) {
console.log('error caught')
})
// Outputs:
// do some other work
// error caught
But if I remove the call to catch an uncaught error is shown. I can even type in the first half, hit enter, see the error, then add the catch and the error goes away. This seems weird to me: how can JavaScript know that a promise will eventually be caught? How would this affect control flow of an application if there's always a chance a promise could later be caught?
I understand promises are typically for asynchronous code, but one could imagine a promise which may return immediately with a validation error or something.
I am aware of try/catch, I'm just trying to understand how this works.
Running in Microsoft Edge 91.0.864.59 (64-bit)

If you're just talking about a message you see in the console that then disappears, then this is just something that occurs in a specific Javascript environment where it decides after-the-fact to rescind/remove a debug message in the console. It does not affect the running of your code in any way. Try three different browsers and you will see different behaviors in each because what shows in the console and when it shows there is up to the implementor of the engine/console, not something that is standardized or something that affects the outcome of your code.
Beyond that, let's discuss issues related to the timing of when a .catch() handler is added. The rejection of your promise is not processed synchronously. The promise state is changed immediately internal to the promise, but it does not synchronously call any .catch() handlers. Instead, a job is inserted into the promise job queue and only when the current chunk of Javascript that is executing is finished and returns control back to the event loop does the promise job get to do its work.
So, in your code, the .catch() handler is added in the current chunk of Javascript execution BEFORE the promise tries to call its catch handlers. Thus, when the promise job that contains the rejection does actually get processed, it is not an uncaught promise because the .catch() handler is already in place.
FYI, typing code into the console and executing it there will not necessarily offer the same timing (and thus errors) as running code in a real script. My comments above are about what happens if you run your whole script at once. I always evaluate asynchronous code in a real execution environment running a complete script, not by typing code into a console and running it pieces at a time.
I can even type in the first half, hit enter, see the error, then add the catch and the error goes away.
That's just a weirdness that occurs in the console when you run pieces of code, but not the whole script. That is not representative of running the whole code in a script.
This seems weird to me: how can JavaScript know that a promise will eventually be caught?
It doesn't. It evaluates whether there's a .catch() handler when the rejection is actually processed (which is via the Promise job queue).
How would this affect control flow of an application if there's always a chance a promise could later be caught?
It's not really an issue because the .catch() handler just needs to be in place before control returns to the event loop when the promise is actually rejected. And, that is usually how code is written so this isn't an issue. You create the promise (or call a function that returns a promise), then you add handlers to it - all in one body of code.
I understand promises are typically for asynchronous code, but one could imagine a promise which may return immediately with a validation error or something.
Neither .then() or .catch() handlers are ever called synchronously, even if the promise is resolved or rejected synchronously. They are always called via the Promise job queue which is always after the current synchronously running Javascript finishes executing and returns control back to the event loop.

Related

How does javascript manage to catch exception in late .catch handler?

The other day I came across the following peace of code:
let promise = Promise.reject(new Error('Promise Failed!')); // 1
setTimeout(() => promise.catch(err => alert('caught')), 1000); // 2
// 3
So I was quite surprised to find out the error was caught in the handler registered one second after the error had occurred.
Now, let me explain step by step the way I perceive this, so you could correct me and tell me where I'm wrong:
During the current macrotask, which is executing this whole script, a promise rejects (1) and since there is no registered rejection handler the control sequentially moves on to the next line.
We call setTimeout passing it a callback function where rejection handler is to be registered (2). But this callback will be scheduled only after a second delay. Furthermore, it will be executed within a separate task.
The execution is on line 3. The current macrotask is done, both stack and task queue are empty. All that's left is to wait for a given delay of 1 second.
One second timeout is complete. Our callback gets to the task queue and right away it is being pushed to the stack which effectively runs it.
During the execution of the callback function, which is part of a new task, .catch handler is registered for the promise rejected one second ago, which took place during the previous and already finished task. Nevertheless, it successfully catches the error.
Does this mean that all this time the error had been somewhere in memory waiting for a chance that maybe .catch handler would be registered later? But what if it had never happened and the number of rejected promises had been a lot more? Will unhandled errors remain to 'hang' in memory waiting for its handler to be registered?
Does this mean that all this time the error had been somewhere in memory waiting for a chance that maybe .catch handler would be registered later?
Yes, it is stored in the promise object. Notice that promises are not just a notification mechanism, they are meant to represent the result of a one-off asynchronous task. The fulfillment value or rejection reason (in your case, the Error instance) and the resolution state are stored on the promise when it settles.
The main idea behind this is that a .then or .catch handler will always be called with the result value, regardless whether the .then() call happens before or after the settling of the promise. This also allows multiple handlers.
Will unhandled errors remain to 'hang' in memory waiting for its handler to be registered?
If you didn't have the setTimeout, the let promise variable and with it the promise object and the error object would have been garbage-collected immediately.
to answer your question directly:
Does this mean that all this time the error had been somewhere in memory waiting for a chance that maybe .catch handler would be registered later?
Yes, we have a WeakMap of pending rejections that keeps track of promises that were rejected but not synchronously handled. Chrome does something similar (I can link to it if you want).
But what if it had never happened and the number of rejected promises had been a lot more?
The assumption in the design of these features is that rejections are pretty rare and are for exceptional cases - so the rejection path is kind of slow. But yes, you could theoretically create a lot of "pending" rejections.
Will unhandled errors remain to 'hang' in memory waiting for its handler to be registered?
We only wait for a microtick - so the flow is:
You create a rejected promise
It has no handler, so it gets put in the WeakMap
All microtasks are run (process.nextTick/Promise.resolve.then)
If it is still rejected, it is an unhandled rejection and it gets logged to the screen / the event is fired.
That is, the rejection is not kept "in memory" for 1000ms (the timer duration) but just for as long as it takes for microtasks to run.

Why is "unhandled promise rejection" a thing?

I understand when the UnhandledPromiseRejectionWarning error happens.
What I don't understand is why the the spec was written in such a way as to allow this behavior.
For example, the following code is bad, if callApi() rejects than we get the UnhandledPromiseRejectionWarning error in Node a similar error in each browser:
class A {
constructor () {
this._stuff = Promise.reject(Error('oops'))
}
getStuff () {
return this._stuff
}
}
const a = new A()
setTimeout(() => {
a.getStuff().catch(err => console.log('I caught it!'))
}, 100)
But why?! I tend to thing of promises as abstracting over when stuff happens.
That's exactly how the promise acts if callApi() is successful: the caller of getStuff() will get the stuff when the data is available.
But the rejection case doesn't work the same way. What I'd expect to happen (if I hadn't been burned by this before) is for the burden of handling the error to fall to the caller of getStuff. That's not how it works, but why?
The detection of an unhandled promise rejection is imperfect in node.js. I don't know exactly how it works internally, but if you don't have a .catch() in a promise chain and that promise rejects, even if you assign it to a variable and then later add a .catch() to it, then it will give you the "unhandled rejection warning".
In your specific case, it is probably because you got back to the event loop with a rejected promise that wasn't caught - your .catch() is only added later on a subsequent event. There's no way for the node.js interpreter to know that you're going to do that. It sees that an event finished executing and a rejected promise was not handled so it creates the warning.
To avoid the warning, you will have to code it differently. You don't really show a real world use so we can see what you're trying to accomplish to make a specific suggestion. As with other types of things like this, the best way to handle it varies depending upon the real world use case.
If you're asking why an unhandled rejection is a warning at all, then that's because it can be a serious error and if there was no warning, then it would simply fail silently and the developer would never be the wiser. It's very much akin to an unhandled exception in synchronous code. That's a serious error and aborts the program. node.js has been notifying for awhile that an unhandled rejection may get the same treatment in the future. For now, it's just a warning.

How to view result of promise without resuming code execution while debugging?

Scenario:
I have new object, I want to play with it live while it's in certain state.
To do that I put debugger where I wanted to investigate it.
This object happens to functions that return promises.
I call that function in console. user.getViews();
I get Promise.unresolve... back
How do I get this promise to work, as in return value. If I had .then that also just return another promise, then only executes if I resume paused environment, which happened due to debugger command.
I tried putting await which didn't work.

If a then function doesn't return a promise, why the next then will be run immediately?

Inside of a then() function, if I didn't return a promise but calling the function directly.
doSomething().then(function () {
doSomethingElse(); //I know I should return doSomethingElse()
}).then(finalHandler);
I know doSomethingElse & finalHandler will run in parallel then instead of running sequentially. But I am still not sure why is that exactly?
doSomething
|-----------------|
doSomethingElse(undefined)
|------------------|
finalHandler(undefined)
|------------------|
When you run code in a .then() handler, you get the following design choices:
1. Return nothing. That leaves the return value undefined and that is a signal to the parent promise that there is no additional asynchronous operation to wait for here so the promise chain can continue running the next steps in the chain.
2. Return a promise. This tells the parent promise that you want to "insert" a promise into the chain and the following .then() handlers should not be called until this promise is resolved. The chain will essentially wait for this promise. If this new promise is ultimately resolved, the next .then() handler will get called. If this new promise is ultimately rejected, the next .catch() handler will get called.
3. Throw an exception. This tells the parent promise that the operation in the .then() handler failed and the parent promise chain immediately becomes rejected and the next .catch() handler will get called.
So, in your case, if doSomethingElse() is an asynchronous operation and you don't return a promise that is connected with that asynchronous operation, then you've just "branched" your promise chain into two separate chains. The main parent chain will continue calling the next .then() handler because you returned nothing. Meanwhile, your doSomethingElse() function is essentially its own parallel promise chain. It could even have it's own .then() handlers as in:
doSomethingElse().then(...).then(...).catch(...)
That would just be a completely separate promise chain that would have no connection at all to the other promise chain except for the timing of when this other promise chain was started. Once it starts, it runs independently from the other chain. This is typically referred to as "branching" in promise terminology. You branch into a new chain. The two run separate form one another. If both branches use asynchronous operations (which they presumably do), those asynchronous operations would be interleaved and both in flight at the same time. The timing of when they both finished would be completely indeterminate (since they have no programmatic relationship in their timing).
Branching to a completely independent promise chain like this is usually a programming error and some promise implementations may report a likely programming error in the console. The reason this is usually an error is there is no way for anyone outside this code to have any way to monitor or catch errors in the branched and independent promise. And promises without error handling are bad. They eat errors silently.
There are certain cases where you legitimately don't change your program behavior if an error happens. Often times when you're closing a file at the end of a long sequence or even just trying to close files after errors have occurred, you just want to make your best efforts to close the file and you don't really have anything more useful to do if the close fails (except perhaps log the failure) so there's no particular reason to try to propagate back that type of failure. But, this should only be done in a very thoughtful way. 99.9999% of the time, errors should be propagated back to the caller and creating a new branched and independent promise chain like this does not propagate its errors back anywhere so it's usually not the right coding strategy.
The function does not need to return a Promise. If nothing was explicitly returned, by default undefined is returned. Functions in Javascript work like that. See the example
function doSomething() {
}
console.log(doSomething());
When you return a Promise from the function in the then chains, then will work only if the returned Promise is resolved. If an exception was occurred, the catch function will work if the last exists.
So actually your code is like
doSomething().then(function () {
doSomethingElse();
return undefined;
}).then(finalHandler); `undefined` is passed into the `finalHandler` function
What about the parallel, they will work not in parallel, but sequentially if the code is then(...).then(...). These then work sequentially. But if your doSomethingElse also returns a Promise, it will have its own sequence of chain. It's flow is independent from the doSomething flow.

Is this promise handling pattern valid? [duplicate]

The word "possibly" suggests there are some circumstances where you can get this warning in the console even if you catch the error yourself.
What are those circumstances?
This is pretty well explained in the docs:
Unhandled rejections/exceptions don't really have a good agreed-on
asynchronous correspondence. The problem is that it is impossible to
predict the future and know if a rejected promise will eventually be
handled.
The [approach that bluebird takes to solve this problem], is to call a
registered handler if a rejection is unhandled by the start of a
second turn. The default handler is to write the stack trace to
stderr or console.error in browsers. This is close to what happens
with synchronous code - your code doesn't work as expected and you
open console and see a stack trace. Nice.
Of course this is not perfect, if your code for some reason needs to
swoop in and attach error handler to some promise after the promise
has been hanging around a while then you will see annoying messages.
So, for example, this might warn of an unhandled error even though it will get handled pretty well:
var prom = Promise.reject("error");
setTimeout(function() {
prom.catch(function(err) {
console.log(err, "got handled");
});
}, 500);

Categories