11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラス内のPromiseでundefined

Posted at

問題

サンプル

class Sample {
    constructor() {
        this.some = 10;
    }

    Start() {
        Promise.resolve()
        .then(this.TaskA)
        .then(this.TaskB)
        .then(this.TaskC)
        .catch((e) => console.log(e));
    }

    TaskA() {
        return new Promise((resolve, reject) => {
            resolve(Math.random());
        });
    }

    TaskB(number) {
        return new Promise((resolve, reject) => {
            resolve(this.some * number);
        });
    }

    TaskC(number) {
        return new Promise((resolve, reject) => {
            console.log(number);
            resolve();
        });
    }
}

const s = new Sample();
s.Start();

TypeError: Cannot read property 'some' of undefined とかなる。thisが参照できてないのでメンバ変数が見えてない。

解決

https://stackoverflow.com/questions/35481367/the-this-object-is-undefined-when-using-promise を参考に解決すると

    Start() {
        Promise.resolve()
        .then(this.TaskA)
        .then(this.TaskB.bind(this))
        .then(this.TaskC)
        .catch((e) => console.log(e));
    }

this参照したい箇所はbindでthisを束縛する。answer内の Promise.bind(this) でやってみる方は解決しなかった。
Typescriptで記述してるときは、 Promise.bind(this) で始めたとしてもメソッドの方は関数型の変数に変えると動いた。

TaskB = (number) => {
	return new Promise((resolve, reject) => {
    	resolve(this.some * number);
    });
}
11
8
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?