中安拓也のブログ

プログラミングについて書くブログ

【JavaScript】Promise チェーンで、戻り値がPromiseのメソッドをつなぐ

戻り値がPromiseのメソッドを順番に実行し、前の処理の結果を次の処理で使いたいという場合があります。そんな時は、Promise チェーンを使いましょう。

バージョン情報

  • Angular: 5.0.1
  • TypeScript: 2.4.2

サンプルコード

下記のコードは、iOSのFace ID/Touch ID認証に関するコードになります。呼び出しているメソッドの戻り値が全てPromiseなので、Promise チェーンで繋げることができます。

.thenのコールバック処理の中で呼びだすPromiseが戻り値のメソッドをreturnしているところがポイント

// 戻り値がPromiseのメソッド
this.keychainTouchId.isAvailable()
    .then((res: any) => {
        console.log(res);
        // 戻り値がPromiseのメソッド
        return this.keychainTouchId.has(BioAuthService.KEY_A);
    }).then((res: any) => {
        console.log(res);
        // 戻り値がPromiseのメソッド
        return this.keychainTouchId
            .verify(BioAuthService.KEYCHAIN_KEY, `ロックを解除してください`);
    }).then((res: any) => {
        console.log(res);
        this.password = res;
        // 戻り値がPromiseのメソッド
        return this.storage.get(BioAuthService.KEY_B);
    }).then((res: any) => {
        console.log(res);
        this.userId = res;
        const params = {
            loginId: this.userId,
            password: this.password,
            deviceToken: null
        };
        this.action.login(params);
    }).catch((error: any) => {
        // catchは一つでよい
        console.error(error);
    });

Promiseの処理を順番に実行していく方法として、ネストしていくやり方もありますが、ネストが深くなっていくとコードが読みづらくなるので、コールバック地獄という言葉に代表されるように、アンチパターンであるとされています。

参考サイト

Promiseを使う - JavaScript | MDN