LoginSignup
4
4

More than 5 years have passed since last update.

Javascript Promiseの使用

Last updated at Posted at 2017-09-21

promise

promiseとは

  • ES6から導入された非同期処理を統一的に扱う方法を定義したオブジェクト。
  • Promiseを使えばネストが深いコールバック嵐から解放される。

superagentを使用したpromise使用例

import request from 'superagent';

const ApiUrl = "http://localhost/";

function testApi(apiName) {
    return new Promise() {
        (resolve, reject) => {
        request.get(ApiUrl + apiName)
            .end(
                (err, res) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(JSON.parse(res.text);
                    }
                }
            );
        }
    };
}

testApi("api1")
  .then(
    (obj) {
      return testApi("api2");
    }
  ).then(
    (obj) {
      return testApi("api3");
    }
  ).then(
    (obj) {
      return testApi("api4");
    }
  ).catch(
    (err) => { console.log("error"); }
  );

promiseを使わないと

import request from 'superagent';

const ApiUrl = "http://example";

function testApi(apiName) {
    request.get(ApiUrl + apiName)
        .end(
            (err, res) => {
                if (err) {
                    return err;
                } else {
                    return res.body;
                }
            }
        );
}

testApi("api1",
    (obj) => {
        testApi("api2",
            (obj) => {
                testApi("api3",
                    (obj) => {
                        testApi("api4",
                            (obj) => {
                                ...
                            },
                            (err) => {
                                console.error(err);
                            }
                        );
                    },
                    (err) => {
                        console.error(err);
                    }
                );
            },
            (err) => {
                console.error(err);
            }
        );
    },
    (err) => {
        console.error(err);
    }
);

の様になり可読性も悪い

Promiseの使い方

  • resolve()を呼ぶと、「処理が成功した状態 (fullfilled)」になる
    • 引数に値を受け取れ、thenのコールバックに渡せる
  • reject()を呼ぶと、「処理が失敗した状態 (rejected)」になる
    • resolveと同様に引数に値を渡せる
    • Errorオブジェクトを渡すのが通例
  • Promiseオブジェクトはthen()メソッドを持ち、処理が成功 or 失敗した際の処理をコールバックとして渡せる
    • 処理が成功だと第1引数の関数を実行
    • 失敗だと第2引数の関数を実行 ※省略可
  • then()が返すのもPromise

参考ページ

4
4
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
4
4