I'm having trouble understanding javaScript promises
. I wrote the following code:
var p = new Promise(function(resolve,reject){
reject(Error("hello world"));
});
setTimeout(()=>p.catch(e=>console.log(e)),5000);
I immediately see this in my Chrome developer console:
But after I wait 5 seconds, the message automatically changes to black like this image:
I've never seen this behaviour before between my javaScript code and a developer console, where my javaScript code can "modify existing content" in the developer console.
So I decided to see if the same situation occurs with resolve
by writing this code:
var p = new Promise(function(resolve,reject){
resolve("hello world");
});
setTimeout(()=>p.then(e=>console.log(e)),5000);
But in this situation, my developer console doesn't show anything until 5 seconds later, to which it then prints hello world
.
Why are the resolve
and reject
treated so differently in terms of when they are invoked?
EXTRA
I also wrote this code:
var p = new Promise(function(resolve,reject){
reject(Error("hello world"));
});
setTimeout(()=>p.catch(e=>console.log("errors",e)),5000);
setTimeout(()=>p.catch(e=>console.log("errors 2",e)),6000);
setTimeout(()=>p.catch(null),7000);
This causes several outputs to the developer console. Red error at time 0, red changes to black at time 5 seconds with the text errors hello world
, then a new error message at time 6 seconds errors 2 hello world
, then a red error message at time 7 seconds. Now I'm very confused on how many times a reject
actually gets invoked....I'm lost...