How to reject a JavaScript promise with `TypeError` by calling the resolve function?

How to reject a JavaScript promise with `TypeError` by calling the resolve function?
javascript
Ethan Jackson

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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolve_function

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.

Answer

I've copied the code from the link in the question:

// 1. Resolving with the promise itself const rejectedResolved1 = new Promise((resolve) => { // Note: resolve has to be called asynchronously, // so that the rejectedResolved1 variable is initialized setTimeout(() => resolve(rejectedResolved1)); // TypeError: Chaining cycle detected for promise #<Promise> });

The comments should explain how and why it produces the described behavior.

Related Articles