3
class ControllablePromise extends Promise {
    constructor() {
        let resolveClosure = null;
        let rejectClosure = null;
        super((resolve, reject) => {
            resolveClosure = resolve;
            rejectClosure = reject;
        });

        this.resolveClosure = resolveClosure;
        this.rejectClosure = rejectClosure;
    }
}
const prom = new ControllablePromise();

async function func(){
  try{
    await prom;
    console.log('done');
  }
  catch(err){
    console.log(err.message);
  }
}


setTimeout(() => {prom.rejectClosure(); console.log('resolved');}, 1000);
func();

I am attempting to create a promise that I can resolve/reject externally. I can do this functionally without issue, just returning a regular promise after I attach the resolve/reject closures to it, but when attempting to turn it into a class I am running into difficulty. The code above throws an error when attempting to await the promise. Why is this happening exactly?

cubesnyc
  • 1,385
  • 2
  • 15
  • 32
  • You have to pass a callback function and call it in the callback function in `super`: https://gist.github.com/domenic/8ed6048b187ee8f2ec75 – jabaa Mar 11 '22 at 18:01
  • Perhaps it is related, but that question revolves around an error being thrown by an attached then, in contrast to an error being thrown when awaiting the promise; – cubesnyc Mar 11 '22 at 18:21
  • 2
    This removes the error message: https://jsfiddle.net/hbk21x8y/ – jabaa Mar 11 '22 at 18:30
  • 1
    "*I am attempting to create a promise that I can resolve/reject externally*" - don't. Why not use promises the normal way? – Bergi Mar 11 '22 at 19:26

0 Answers0