Promise override causes then calls to error

前端 未结 1 915
北海茫月
北海茫月 2021-01-27 05:03

I have the following sample code.

class test extends Promise {
    constructor(executor) {
        super(executor)
    }

    static getPromise() {
        retur         


        
相关标签:
1条回答
  • 2021-01-27 06:00

    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(…);
    
    0 讨论(0)
提交回复
热议问题