LoginSignup
1
0

More than 5 years have passed since last update.

Google Closure LibraryでDeferred

Last updated at Posted at 2012-09-17

goog.async.Deferred.whenの第一引数はgoog.async.Deferredオブジェクト。ただし、通常の値が渡された場合は即座にcallbackの引数として実行される。

var value,
    isImmediate = false;
if (isImmediate) {
    value = 3;
} else {
    value = new goog.async.Deferred();
    setTimeout(function() { value.callback(6); }, 2000);
}

var d = goog.async.Deferred.when(value, alert);

jQueryのwhenのように、複数の処理がすべて終わってからなにか処理を実行する。

var def1 = new goog.async.Deferred();
var def2 = new goog.async.Deferred();
def1.awaitDeferred(def2);

setTimeout(function () {
    console.log('def1');
    def1.callback();
}, 5000);

setTimeout(function () {
    console.log('def2');
    def2.callback();
}, 7000);

goog.async.Deferred.when(def1, function () {
    alert('ok');
});

// def1
// def2
//=> alert 'OK'
//の順で処理が実行される。
//def1が終わってから、ではなく、同時に処理が走るのがポイント。
1
0
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
1
0