LoginSignup
19
15

More than 5 years have passed since last update.

JavaScript(ECMA Script 2015)のクラスでのPromiseの書き方

Posted at

JavaScript(ECMA Script 2015 / ECMA Script 6)ではクラス機能や非同期処理を扱うPromiseクラスが使えます。Promiseはスコープがとち狂ってしまうことがあるので、対処方法をまとめました。

then()でアロー関数を使え

結論からいうと、Promiseインスタンスのthen()メソッドでスコープが変わるので、ここにアロー関数を使うと良いです。

// プロミスの書き方
new Promise((resolve) => {
    // 一秒待って
    setTimeout(()=>{
      // プロミス終わり
      resolve();
    }, 1000);
  })
  .then(() => {
    // スコープは、ずれないよ!
    console.log(this);
  });

サンプルで理解しよう

スコープをクラスに閉じ込めた場合で検証します。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script>
    "use strict";

    /** Promise 内包クラス */
    class Hoge {
      constructor(){
        this.piyo = "ぴよ";
      }
      getPromise(){
        // 非同期処理を挟む
        return new Promise((resolve) => {
          // 一秒待って
          setTimeout(()=>{
            // プロパティーに代入
            this.piyo = "もじゃ";
            // プロミス終わり
            resolve();
          }, 1000);
        });
      }
    }

    /** Promise 利用クラス */
    class Main {
      constructor(){
        var hoge = new Hoge();
        // プロミスの書き方
        hoge.getPromise()
          // 一秒後に
          .then(() => {
            // スコープは、ずれないよ!
            console.log(hoge.piyo);
            console.log(this);
          });
      }
    }

    // 実行
    new Main();

  </script>
</head>
<body>

</body>
</html>

実行結果は次の結果となりました。this.piyoもじゃとなり、console.log(this)ではMainとなりました。想定通りですね!

もじゃ
Main {}
19
15
0

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
19
15