const p1 = Promise.resolve({
then(onFulfill, onReject) {
onFulfill('fulfilled!');
},
});
console.log(p1 instanceof Promise)
p1.then(
(v) => {
console.log(v);
},
(e) => {
},
);
const thenable = {
then(onFulfilled) {
throw new TypeError('Throwing');
onFulfilled('Resolving');
},
};
const p2 = Promise.resolve(thenable);
p2.then(
(v) => {
},
(e) => {
console.error(e);
},
);
const thenable = {
then(onFulfilled) {
onFulfilled('Resolving');
throw new TypeError('Throwing');
},
};
const p3 = Promise.resolve(thenable);
p3.then(
(v) => {
console.log(v);
},
(e) => {
},
);
Nested thenables will be "deeply flattened" to a single promise.
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled({
then(onFulfilled, onRejected) {
onFulfilled(42);
},
});
},
};
Promise.resolve(thenable)
.then((v) => {
console.log(v);
});
Warning: Do not call Promise.resolve()
on a thenable that resolves to itself. That leads to infinite recursion, because it attempts to flatten an infinitely-nested promise.
const thenable = {
then(onFulfilled, onRejected) {
onFulfilled(thenable);
},
};
Promise.resolve(thenable)