2017-04-14 5 views
0

asyncメソッドコールをTypescriptで取り消そうとしています。最初のバージョンはObject.setPrototypeOf(..)なしだったが、それは私がしようとしているときon the TypeScript GitHub pageTypescript:Promiseのサブクラス/拡張は、実行時に 'TypeError:undefined is promise'を返します。

をお勧めし

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. 

     Object.setPrototypeOf(this, CancelablePromise.prototype); 

    } 

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

:これを行うには

、私はPromiseから継承する新しい約束のタイプを、作成しています

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); 

エラー:

それを使用するために、私は、実行時エラー(なしコンパイルエラー)を取得します
(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) 

私は間違っていますか?私はES6でサブクラスPromisestackoverflow questionを参照してください)を参照してください、私はそれもタイプスクリプトで期待しています。

活字体2.1を使用すると、あなたはTypeScript Playgroundでコードを実行する場合、同じ結果を参照してください「実行」をクリックし、新しいページにコンソール(F12)を確認することができます

をES5ターゲット。

Error in console

どのように私は、このランタイムエラーを解決するのですか?


PS:stackoverflowのに関連するエラーがhereあるが、コンパイルエラーことと解きます。私はコンパイルとランタイムエラーを分割しました。

+0

「Object.setPrototypeOf(this、CancelablePromise.prototype);」の理由は何ですか? – unional

+0

@unionalそれはリンク(投稿にも含まれています)から "推奨事項 - スーパー(...)コールの直後に手動でプロトタイプを手動で調整することができます。 – Julian

答えて

1

私はあなたの例を簡略化しました。これはエラーなしで実行されます。

interface CancelablePromise<T> extends Promise<T> { 
    cancel:() => void; 
} 

class Test { 
    postFileAjax<T>(file: File): CancelablePromise<T> { 
     const promiseFunc = (resolve) => { resolve() }; 
     const promise = new Promise<T>(promiseFunc); 
     const cancel =() => { console.log("cancel!") }; 
     const cancelablePromise = Object.assign(promise, { cancel }); 
     return cancelablePromise; 
    } 
} 

const test = new Test(); 
const testPromise = test.postFileAjax(null); 
testPromise.cancel(); 

TypeScript Playground

  • 私はインターフェイスの継承ではなく、新しいクラスを使用していました。
  • promisecancelの機能をコピーしました。
関連する問題