LoginSignup
187
193

More than 5 years have passed since last update.

jQueryのDeferredの基本的な使い方メモ

Last updated at Posted at 2014-05-03

すぐわからなくなるので基本的なところだけメモ。

async(function() {
    console.log('async');
});
console.log('hoge');

/**指定した関数を 1 秒後に実行する*/
function async(f) {
    setTimeout(f, 1000);
}

これを実行すると、

実行結果
hoge
async

とコンソールに出力される。

しかし、どうしても非同期処理の後で hoge を出力させたい場合に Deferred を使う。

var d = new $.Deferred();

async(function() {
    console.log('async');
    d.resolve();
});

d.promise().then(function() {
    console.log('hoge');
});

/**指定した関数を 1 秒後に実行する*/
function async(f) {
    setTimeout(f, 1000);
}
実行結果
async
hoge
  • new $.Deferred()Deferred のオブジェクトを生成する。
  • 非同期処理が完了した時点で、生成しておいた Deferred オブジェクトの resolve() メソッドを実行する。
  • Deferred オブジェクトの promise() メソッドを実行し、その戻り値(promise オブジェクト)の then() メソッドに非同期処理の後に実行したい処理を渡す。

then() はメソッドチェーンができるので、

var d = new $.Deferred();

async(function() {
    console.log('async');
    d.resolve();
});

d.promise()
.then(function() {
    console.log('hoge');
})
.then(function() {
    console.log('fuga');
});

/**指定した関数を 1 秒後に実行する*/
function async(f) {
    setTimeout(f, 1000);
}

という風に書ける。

実行結果
async
hoge
fuga

ただし、このままだと2つ目の then() は1つ目の then() が終了するとすぐ実行される。

なので、

var d = new $.Deferred();

async(function() {
    console.log('async');
    d.resolve();
});

d.promise()
.then(function() {
    // ★1つ目の then() が非同期処理
    async(function() {
       console.log('hoge'); 
    });
})
.then(function() {
    console.log('fuga');
});

/**指定した関数を 1 秒後に実行する*/
function async(f) {
    setTimeout(f, 1000);
}

こんな実装になっていると、

実行結果
async
fuga
hoge

となる。

1つ目の then() の非同期処理が終わってから2つ目の then() を実行したい場合は、1つ目の then() で新しい promise オブジェクトを返す。

var d = new $.Deferred();

async(function() {
    console.log('async');
    d.resolve();
});

d.promise()
.then(function() {
    var d2 = new $.Deferred();

    async(function() {
        console.log('hoge');
        d2.resolve();
    });

    return d2.promise();
})
.then(function() {
    console.log('fuga');
});

/**指定した関数を 1 秒後に実行する*/
function async(f) {
    setTimeout(f, 1000);
}
実行結果
async
hoge
fuga

参考

187
193
1

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
187
193