Trying to understand promises.
Invoking .then() on a promise, returns a new promise. The two promises are different objects.
let promise = new Promise(function(resolve, reject) {resolve('ok');});
let obj2 = promise.then(
function(result){/*do nothing*/},
function(error){/*do nothing*/}
);
alert(obj2 instanceof Promise); //true
alert(promise === obj2); //false
I'm wondering where the executor for the 2nd promise is and what it's defaulted to. Certainly, trying to create a promise with no executor throws an error.
let promise = new Promise(); //TypeError: undefined is not a function
The reason I want to know this is on account of the following code.
<html>
<head>
<title>chained promises</title>
<script type='module'>
window.onload = function(){
new Promise(function(resolve, reject) {
setTimeout(function(){
(Math.random()>0.5) ? resolve('ok') : reject(new Error('something bad happened'))},
1000
);
}).then(
function(result){
document.getElementById('p').innerHTML += `then #1 result handler: ${result}<br>`;
return result;
},
function(error){
document.getElementById('p').innerHTML += `then #1 error handler: ${error}<br>`;
return error;
}
).then(
function(result){
document.getElementById('p').innerHTML += `then #2 result handler: ${result}<br>`;
},
function(error){
document.getElementById('p').innerHTML += `then #2 error handler: ${error}<br>`;
}
);
}
</script>
</head>
<body>
<p id='p' class='result'></p>
</body>
</html>
output:
then #1 error handler: Error: something bad happened
then #2 result handler: Error: something bad happened
Half the time the promise is resolved, and it's otherwise rejected.
When the initial promise is rejected, as above, the error handler of the first .then is invoked. However, when the 2nd .then is reached, its the result handler that gets invoked. Since the 2nd .then is a method of the 2nd promise, I'm wondering where the executor for that second promise is.
Could anyone clarify?