I have the following sample code.
class test extends Promise {
constructor(executor) {
super(executor)
}
static getPromise() {
retur
Why are these not equivalent, and why is this erroring?
Your overridden constructor does never call the executor
and pass it the promise resolving functions (resolve
and reject
). They are important! You cannot subclass Promise
and change the interface like that.
Why does this throw an error when you call new test()
that doesn't use the constructor? It does not. It throws the error when you call t.then(…)
, which tries to construct a new promise (for its return value) and uses t
's constructor for that. It does pass a proper executor callback, and expects it to be called synchronously with resolve
and reject
- which your code does not do. After the call, it bitches about not having got two functions.
How can I make this work as I expect?
Don't use promise subclassing. There's no reason for it. You just want to have a normal function that returns a promise. Use
const test = {
getPromise() {
return Promise.resolve(true)
}
};
test.getPromise().then(…);
or
function test() {
return Promise.resolve(true);
}
test().then(…);