2
3

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.

Deferred

Posted at

Deferred

Deferredとは「鍵付きのタイムカプセル」

デモ:http://codepen.io/mo4_9/pen/xOBWbx

関数内でDeferredを生成し、
何らかの非同期処理を行ったのち、
Promiseを返すパターン

お決まりのパターン|プリロード処理
function preload(url) {
  const defer = $.Deferred(); // Deferredオブジェクト生成
  let loadCount = 0;
  
  for(let val of url) {
    const img = new Image();
    img.src = val;
    img.onload = () => { // 非同期処理
      loadCount += 1;
      console.log(loadCount);
      if(loadCount == url.length) {
        defer.resolve(); // 通信成功
      }
    }
  };
 
  return defer.promise(); // Deferredからpromiseを取り出す
}

const url = [
  'http://placeimg.com/640/360/people',
  'http://placeimg.com/640/360/sepia',
  'http://placeimg.com/640/360/any'
]

const promise = preload(url);

promise.done( () => {
  console.log('all loaded');
})

$.ajax()は、それ自体がPromiseを返しているので
resolve()する必要はない

then

複数のAjax通信を順番に行いたい場合に便利
thenを使わないと複雑な入れ子構造になる

デモ:http://mo49.tokyo/qiita/20160820/then.html

順番にAjax通信を行う
const promise1 = $.get('ajax1.php');
const promise2 = promise1.then( (data) => {
  return $.get('ajax2.php');
});
const promise3 = promise2.then( (data) => {
  return $.get('ajax3.php');
});
promise3.done(function(data) {
  console.log('終了');
});

when

http://api.jquery.com/jQuery.when/
http://www.jquerystudy.info/reference/deferred/when.html

複数のPromiseを結合して、合体したPromiseを返す

デモ:http://mo49.tokyo/qiita/20160820/when.html

複数のPromiseを結合する
const promise1 = $.get('ajax1.php');
const promise2 = $.get('ajax2.php');

const promise = $.when(promise1, promise2);
promise.done( onSuccess );
promise.fail( onFailure );

function onSuccess (data1, data2) {
  $txt1.text( data1 );
  $txt2.text( data2 );
  console.log('両方成功');
}
function onFailure (data) {
  console.log('どちらか失敗');
}

Promiseの数が定まっていない場合は可変長引数を使う

デモ:http://mo49.tokyo/qiita/20160820/when2.html

可変長のPromiseを渡す
let promises = [];

promises.push( $.get('ajax1.php') );
promises.push( $.get('ajax2.php') );
promises.push( $.get('ajax3.php') );

$.when.apply(null, promises).done( (...arg) => {
  for (val of arg) {
    $(document.body).append('<div>'+val+'</div>');
  }
});

参考
よく分かる jQuery Deferred
はじめてajaxを使うときに知りたかったこと

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?