Using Typescript ^3.8. I am building a BrokenPromise
class which extendsPromise
but is supposed to return a promise that never resolves. Before building the class, this is how I built such a promise:
const p = new Promise(resolve => {});
Figuring this would be simple, I tried this:
class BrokenPromise extends Promise {
constructor() {
super(resolve => {});
}
}
The Typescript compiler doesn't complain, so then I try to use it like so:
Promise.race([
new BrokenPromise().then(() => { log('SHOULD NEVER RUN'); }),
sleep(2).then(() => { log('SHOULD ALWAYS WIN THE RACE') })
]);
But the BrokenPromise.then
fails with this error:
TypeError: Promise resolve or reject function is not callable at Promise.then
Why is this happening? The code below works but smells:
class BrokenPromise extends Promise {
super(resolve => {});
return new Promise(resolve => {});
}
Update 1: Solved (thanks Nick Parsons)
export class BrokenPromise extends Promise<any> {
constructor(executor = (resolve, reject?) => {}) {
super(executor);
}
}
The problem with my original code was that .then
behind the scenes passes an executor function to the constructor and expects resolve
or reject
to be called, but my code ignored it. The new code above passes it on to the parent constructor where it gets treated as expected.