Note:
This question has been closed as a duplicate, though I can’t see how it is the same as the referenced question.
Here I am asking about extending the Promise class. There the question is different, though it does mention a common goal of accessing the executor functions.
I am trying to extend JavaScript Promises using ES6 class
syntax. In the extended class, I want to make the resolve
and reject
functions more accessible.
Here is a test script:
var executor = {};
var promise = new Promise((resolve,reject) => {
executor = {resolve,reject};
});
promise.resolve = message => { executor.resolve(message ?? true); };
promise.reject = message => { executor.reject(message ?? false); };
document.querySelector('button#ok').onclick = event => promise.resolve('OK');
document.querySelector('button#cancel').onclick = event => promise.reject('Cancelled');
promise
.then(result => {console.log(result); })
.catch(error => {console.log(error); });
<button id="ok" type="button">OK</button>
<button id="cancel" type="button">Cancel</button>
Ultimately the code will be part of a pseudo dialog box.
As it stands, the Promise constructor stores the resolve
and reject
functions in an external variable, and two additional methods are bolted on to the resulting promise
object.
I thought it should be s simple task to do this in an an inherited object:
class Promise2 extends Promise {
constructor() {
// add the resolve and resolve functions as instance methods
}
}
The problem is that the constructor needs to call super()
to instantiate this
and I can’t see how I can proceed from there.
Is it possible to extend Promise this way, or is there another way to store a reference to the resolve
and reject
functions in the object itself?