Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Last active May 27, 2018 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtnabe/a05eae870a0959c7a35a77b7dab38255 to your computer and use it in GitHub Desktop.
Save wtnabe/a05eae870a0959c7a35a77b7dab38255 to your computer and use it in GitHub Desktop.
trial and comparison between jQuery.deferred and es6 Promise object

Promise試してみた

jQuery.deferred

jQuery.deferred で実験。fail() は jQuery 用語で、ES2015 だと catch() になる。

1) 単純な成否

$.getJSON('/api1')
  .then(function() {
     // success
  })
  .fail(function() {
    // failure
  });

これだけだと if then else のように動く。

2) 連続する一まとまりの処理

$.getJSON('/api1')
  .then(function() {
    return $.getJSON('/api2');
  })
  .fail(function() {
    // failure for api1 and api2
  });

then() の中で非同期処理を実行して「Promiseを返せば」どちらで失敗しても同じ fail() を通過する

3) 異なるPromiseの処理

$.getJSON('/api1')
  .then(function() {
    $.getJSON('/api2')
      .then(function() {
        // success
      })
      .fail(function() {
        // failure for api2
      });
    })
  .fail(function() {
    // failure for api1
  });

非同期ではあるけど if then の入れ子のような感じでも書ける。中の fail() でエラーを拾っておけば外の fail() まで伝播することはない。

Promise ( ES2015 )

Browserify + Umbrellajs + ES2015 Promise で実験。jQuery の $.getJSON() とほぼ同じ動きをして Promise を返す wrapper 関数 u.getJSON() を定義。u.ajax() は特に指定しなくても JSON string だったら自動的に parse してくれる。

ES2015 の Promise は jQuery.deferred と違って失敗時は catch() で拾う。

wrapper

var u = require('umbrellajs');

u.getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    u.ajax(url,
           {method: 'GET'},
           function(err, data) {
             if ( err ) {
               reject(err);
             } else {
               resolve(data);
             }
           }
          );
  });
}

1) 単純な成否

u.getJSON('/api1')
  .then(function(data) {
    // success
  })
  .catch(function(e) {
    // failure
    console.log(e + ' : api failed.');
  });

2) 連続する一まとまりの処理

u.getJSON('/api1')
  .then(function() {
    // success
    return u.getJSON('/api2');
  })
  .catch(function() {
    // failure for api1 and api2
  });

3) 異なるPromiseの処理

u.getJSON('/api1')
  .then(function() {
    u.getJSON('/api2')
      .then(function() {
        // success
      })
      .catch(function() {
        // failure for api2
      });
    })
  .catch(function() {
    // failure for api1
  });

おまけ ( ES6 arrow function )

u.getJSON('/api1')
  .then(() => {
    // success
  })
  .then(() => {
    return u.getJSON('/ap2')
      .then(data => {
        console.log('fast api succeeded.');
      })
      .catch(e => {
        console.log('fast api failed.');
      });
  })
  .catch(e => {
    console.log(e + ' : api failed.');
  });

babel-es2015-preset で実験。基本的には function() {}() => {} に置き換えれば ok. 引数が1つの時には () を省略できる。引数が1つで単純な値を返すのであれば

  • => { statement }

ではなく

  • => expression

も組み合わせるとかなりスッキリ書ける

(e) => { return e * 2 }
e => e * 2

が、日常的に読み書きしていないとかえって読みにくい気もする。本当に単純なことをやっていて、勘違いの起きようがない場合を除いて (){} の省略はしない方が無駄にハマりにくいだろう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment