Skip to content

Extending Promise gives runtime error: undefined is not a promise #15202

@304NotModified

Description

@304NotModified

I also asks this on Stackoverflow, but I think this is a bug:

I'm trying to cancel my async method call in Typescript.

To do this, I have created a new Promise type, which inherits from Promise.

My first version was without the Object.setPrototypeOf(..), but I took it for here

TypeScript Version: 2.2.0, targeting ES5

Code

class CancelablePromise<T> extends Promise<T>{

    public cancelMethod: () => void;
    constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
        super(executor);
        // Set the prototype explicitly.
        // See: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
        Object.setPrototypeOf(this, CancelablePromise.prototype);
        
    }

    //cancel the operation
    public cancel() {
        if (this.cancelMethod) {
            this.cancelMethod();
        }
    }
}

class Test{

    async postFileAjax<T>(file: File): CancelablePromise <T> { 

        var promiseFunc = (resolve) => { resolve() };
        var promise = new CancelablePromise<T>(promiseFunc);
        promise.cancelMethod = () => { console.log("cancel!") };
    
        return promise;
    }
}

var test = new Test();
test.postFileAjax(null);

Expected behavior:
No runtime error, or compile error if not allowed.

And of course working promise if no error.

Actual behavior:

Got a run-time error

Error:

(unknown) Uncaught TypeError: undefined is not a promise
    at CancelablePromise.Promise (<anonymous>)
    at new CancelablePromise (<anonymous>:44:28)
    at __awaiter (<anonymous>:7:12)
    at Test.postFileAjax (<anonymous>:62:16)
    at <anonymous>:75:6
    at HTMLButtonElement.excuteButton.onclick (https://www.typescriptlang.org/play/playground.js:242)

Link to playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptES6Relates to the ES6 Spec

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions