LoginSignup
2
3

More than 5 years have passed since last update.

今更$.Deferredの使い方

Last updated at Posted at 2018-03-13

はじめに

IE11に対応することになったらPromiseが使えず、今更$.Deferredを学習したので記録

  • 参考記事

定義側

function post(url, data) {
  const defer = new $.Deferred;
  $.ajax({
    url: url,
    data: data,
    type: 'json',
    method: 'POST',
    success: function(res) { defer.resolve(res); },
    error: function(err) { defer.reject(err); }
  });
  return defer.promise();
}

利用側

単発

post('/zun', { doko: 'kiyoshi!' })
  .done(function(res) {
    console.log(res);
  })
  .fail(function(err) {
    console.error(err);
  });

順々に処理したい場合

post('/zun', { zun: 'zun' })
  .then(function(res) {
    console.log(res);
    return post('doko', { doko: 'doko' });
  })
  .done(function() {
    console.log('kiyoshi!');
  })
  .fail(function(err) {
    console.error(err);
  });

複数並列に処理したい場合

$.when(
    post('/zun', { zun: 'zun' }),
    post('/doko', { doko: 'doko' })
  )
  .done(function() {
    console.log('kiyoshi!')
  })
  .fail(function(err) {
    console.error(err);
  });
2
3
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
2
3