CallBackのネスト地獄をasync/await でリファクタリングするメモ

リファクタリング対象コード

    anyMethoid(){
      this.returnPromiseMethod1().then(result1 => {
        if (result1.data) {
          // result1を取得してからしたい何かの処理...
          this.returnPromiseMethod2().then(result2 => {
            if (result2.data) {
            // result1とresult2を取得してからしたい何かの処理...
            }
          }
        }
      }
    }

async/await でリファクタリング

    async anyMethoid(){
      let result1 = await this.returnPromiseMethod1()
      if (!result1.data) return
      // result1を取得してからしたい何かの処理...
      let result2 = await this.returnPromiseMethod2()
      if (!result2.data) return
      // result1とresult2を取得してからしたい何かの処理...
    }

async/awaitによるthenthenthen…からの脱出。コード内容は適当です。 asyncは暗黙的にPromiseを返してawaitはPromiseの解決を待ちます。

参考リンク

developer.mozilla.org