LoginSignup
47
57

More than 5 years have passed since last update.

$.ajax の done, fail, always を Promise の then, catch に置き換える

Last updated at Posted at 2017-03-10

はじめに

jQuery 3 から $.DeferredPromises/A+ という Promise の標準規格に準拠するようになった。そこで、せっかくなので $.ajax のコールバック処理も thencatch で書いてみることにした。

done, fail, always を使う場合

$.ajax({
  type: 'GET',
  url: '/soul_gems',
  dataType: 'json'
})
  .done((data, textStatus, jqXHR) => {
    console.log('done', jqXHR.status);
  })
  .fail((jqXHR, textStatus, errorThrown) => {
    console.log('fail', jqXHR.status);
  })
  .always(() => {
    console.log('always');
  });

成功した場合

done 200
always

失敗した場合

fail 403
always

then, catch を使う場合

$.ajax({
  type: 'GET',
  url: '/soul_gems',
  dataType: 'json'
})
  .then((...args) => { // done
    const [data, textStatus, jqXHR] = args;

    console.log('done', jqXHR.status);
  })
  .catch((...args) => { // fail
    const [jqXHR, textStatus, errorThrown] = args;

    console.log('fail', jqXHR.status);
  })
  .then(() => { // always
    console.log('always');
  });

成功した場合

done 200
always

失敗した場合

fail 403
always
47
57
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
47
57