2

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.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • I think you should try declaring your promise first then calling `.then`. I don't think you can call `new Promise().then`. Maybe try `const p = new BrokenPromise` and then call `p().then` – Nicholas Porter Nov 18 '20 at 01:44
  • Hi. At the bottom of my post, I explained that if I change the constructor of `BrokenPromise`, then the same `new BrokenPromise().then()` works. So something else is going on – BeetleJuice Nov 18 '20 at 01:46
  • 2
    Have you seen this thread: [Promise override causes then calls to error](https://stackoverflow.com/q/47312427), you can probably make it work by using something like: `constructor(executorFn = resolve => {}) { super(executorFn);}`, or just don't subclass the promise (like the linked answer suggests) – Nick Parsons Nov 18 '20 at 01:59
  • @NickParsons Thanks, you helped me solve my issue. if you'd like to get credit for this, please add it as an Answer to the post. – BeetleJuice Nov 18 '20 at 02:21
  • @BeetleJuice nw, might be better to close as a dupe of the linked questions – Nick Parsons Nov 18 '20 at 02:33

0 Answers0