While reading the promise documentation I came across this statement:
If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a
TypeError.
which I can't understand, what value should I pass to resolve() to reject the promise with TypeError?
I would like to see some example code that reproduces this behavior.
A promise can resolve to another promise, but not to itself.
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve(myPromise), 0);
});
myPromise.then(function() {
console.log("normal")
}).catch(function(ex) {
// this error is TypeError
console.log(ex.message)
console.log(ex instanceof TypeError)
})
But wait, let's try to trick javascript into circular resolution loop with a promise that resolves to a promise that resolves to the first one.
let myPromise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve(myPromise2), 0);
});
let myPromise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve(myPromise1), 0);
});
myPromise1.then(function() {
console.log("normal")
}).catch(function(ex) {
// this error is TypeError
console.log(ex.message)
console.log(ex instanceof TypeError)
})
A surprising result, I was expecting a TypeError. But it didn't come and both Promises are now pending, forever.