Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

Deferred

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を使うときに知りたかったこと

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?