LoginSignup
50
51

More than 5 years have passed since last update.

ES6のPromiseを使ってsuperagentでapiを叩く

Last updated at Posted at 2015-08-13

AJAXを使うときは、素の状態で使うよりもライブラリから使ったほうがいいです。現在のプロジェクトはReact.jsを使っていますが、DOM操作は必要ないので、足りないのはAJAXを利用するだけのライブラリが欲しいです。そこで、superagentがシンプルで目的に合致します。

ES6ではPromiseが使えます。非同期通信を使うときは、Promiseを使えばネストが深いコールバック嵐から解放された約束の地へ行けます。それではsuperagnetによるAJAXの非同期通信をES6のPromiseを使って利用してみます。

import request from 'superagent';

function callApi(apiName) {
  return new Promise() {
    (resolve, reject) => {
      request.get("http://localhost/" + apiName)
        .end(
          (err, res) => {
            if (err) {
              reject(err);
            } else {
              resolve(JSON.parse(res.text);
            }
          }
        );
    }
  };
}

callApiはPromiseを返します。これを利用する側は、

callApi("api1")
  .then(
    (obj) => {
      console.debug(obj);
    }
  ).catch(
    (err) => { console.error(err); }
  );

です。連続して呼び出す場合は、

callApi("api1")
  .then(
    (obj) => {
      console.debug(obj);
      return callApi("api2");
    }
  ).then(
    (obj) => {
      console.log("api2");
      console.debug(obj);
    }
  ).catch(
    (err) => { console.error(err); }
  );

となります。Promiseを使わないと、

callApi("api1",
  (obj) => {
    callApi("api2",
      (obj) => {
        console.info("api2");
        console.debug(obj);
      },
      (err) => {
        console.error(err);
      }
    );
   },
  (err) => {
    console.error(err);
  }
);

となります。コードの読みやすさは歴然と違いますよね。特にネストが深くなると、悪夢です。

50
51
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
50
51