45
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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
45
56
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
45
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?