Object Deferred

Constructor
Constructor Attributes Constructor Name and Description
  Deferred()
Instance Methods
Method Attributes Method Name and Description
  Deferred#call(val) //=> Deferred
  Deferred#cancel() //=> Deferred
  Deferred#error(fun) //=> Deferred
  Deferred#fail(val) //=> Deferred
  Deferred#next(fun) //=> Deferred
Value Properties
Value Attributes Value Name and Description
  Deferred.ok
  Deferred.ng
  Deferred.methods
Function Properties
Method Attributes Method Name and Description
  Deferred.call(fun, args) //=> Deferred
  Deferred.chain(arguments) //=> Deferred
  Deferred.connect(funo, options) //=> function(...[*]):Deferred
  Deferred.define(obj, list) //=> function():Deferred
  Deferred.earlier(dl) //=> Deferred
  Deferred.isDeferred(obj) //=> boolean
  Deferred.loop(n, fun) //=> Deferred
  Deferred.next(fun) //=> Deferred
  Deferred.parallel(dl) //=> Deferred
  Deferred.register(name, fun)
  Deferred.repeat(n, fun) //=> Deferred
  Deferred.retry(retryCount, funcDeferred, options) //=> Deferred
  Deferred.wait(sec) //=> Deferred

Constructor

Deferred()

Create a Deferred object
  var d = new Deferred();
  // or this is shothand of above.
  var d = Deferred();
  Deferred.define();

  $.get("/hoge").next(function (data) {
      alert(data);
  }).

  parallel([$.get("foo.html"), $.get("bar.html")]).next(function (values) {
      log($.map(values, function (v) { return v.length }));
      if (values[1].match(/nextUrl:\s*(\S+)/)) {
          return $.get(RegExp.$1).next(function (d) {
              return d;
          });
      }
  }).
  next(function (d) {
      log(d.length);
  });

Instance Methods

Deferred#call(val) //=> Deferred

Parameters

val : *
Value passed to continuation.

Returns

Deferred this
Invokes self callback chain.
  function timeout100 () {
    var d = new Deferred();
    setTimeout(function () {
       d.call('value');
    }, 100);
    return d;
  }

Deferred#cancel() //=> Deferred

Returns

Deferred this
Cancel receiver callback (this is only valid before invoking any callbacks)

Deferred#error(fun) //=> Deferred

Parameters

fun : function(this:Deferred|...[*]):*
Errorback of continuation.

Returns

Deferred Next Deferred object
Create new Deferred and sets `fun` as its errorback. If `fun` not throws error but returns normal value, Deferred treats the given error is recovery and continue callback chain.
  var d =  new Deferred();

  d.
  next(function () {
    alert(1);
    throw "foo";
  }).
  next(function () {
    alert('not shown');
  }).
  error(function (e) {
    alert(e); //=> "foo"
  });

  d.call();

Deferred#fail(val) //=> Deferred

Parameters

val : *
Value of error.

Returns

Deferred this
Invokes self errorback chain. You can use this method for explicit errors (eg. HTTP request failed)
  function http (url) {
    var d = new Deferred();
    var x = new XMLHttpRequest();
    x.onreadystatechange = function () {
      if (x.readyState == 4) {
        if (x.status == 200) d.call(x); else d.fail(x);
      }
    };
    return d;
  }

Deferred#next(fun) //=> Deferred

Parameters

fun : function(this:Deferred|...[*]):*
Callback of continuation.

Returns

Deferred Next Deferred object
Create new Deferred and sets `fun` as its callback.
  var d = new Deferred();

  d.
  next(function () {
    alert(1);
  }).
  next(function () {
    alert(2);
  });

  d.call();

Value Properties

Deferred.ok

Parameters

x
Default callback function

Deferred.ng

Parameters

x
Default errorback function

Deferred.methods

Default export methods

Function Properties

Deferred.call(fun, args) //=> Deferred

Parameters

fun : function(...[*]):*
Function to call
args : ...*
Arguments passed to `fun`

Returns

Deferred
`call` function is for calling function asynchronous.
  // like tail recursion
  next(function () {
      function pow (x, n) {
          function _pow (n, r) {
              print([n, r]);
              if (n == 0) return r;
              return call(_pow, n - 1, x * r);
          }
          return call(_pow, n, 1);
      }
      return call(pow, 2, 10);
  }).
  next(function (r) {
      print([r, "end"]);
  });

Deferred.chain(arguments) //=> Deferred

Parameters

arguments : ...[(Array.<function(*):*>|Object.<string|function(*):*>|function(*):*)]
Process chains

Returns

Deferred
Construct Deferred chain with array and return its Deferred. This is shorthand for construct Deferred chains.
 return chain(
     function () {
         return wait(0.5);
     },
     function (w) {
         throw "foo";
     },
     function error (e) {
         alert(e);
     },
     [
         function () {
             return wait(1);
         },
         function () {
             return wait(2);
         }
     ],
     function (result) {
         alert([ result[0], result[1] ]);
     },
     {
         foo: wait(1),
         bar: wait(1)
     },
     function (result) {
         alert([ result.foo, result.bar ]);
     },
     function error (e) {
         alert(e);
     }
 );

Deferred.connect(funo, options) //=> function(...[*]):Deferred

Parameters

funo : (function(...[*]):*|*)
Target function or object
options : ({ok:number|ng:number|target:*}|string)
Options or method name of object in arguments[0]

Returns

function(...[*]):Deferred
Connect a function with Deferred. That is, transform a function that takes a callback into one that returns a Deferred object.
  var timeout = Deferred.connect(setTimeout, { target: window, ok: 0 });
  timeout(1).next(function () {
      alert('after 1 sec');
  });

  var timeout = Deferred.connect(window, "setTimeout");
  timeout(1).next(function () {
      alert('after 1 sec');
  });

Deferred.define(obj, list) //=> function():Deferred

Parameters

obj : Object
A object which this method should export to
list : Array.<string>=
List of function names (default Deferred.methods)

Returns

function():Deferred The Deferred constructor function
Export functions to obj.

Deferred.earlier(dl) //=> Deferred

Parameters

dl : (Array.<Deferred>|Object.<string|Deferred>)
Deferred objects wanted to wait

Returns

Deferred
Continue process when one deferred in `deferredlist` has completed. Others will be canceled. parallel ('and' processing) <=> earlier ('or' processing)

Deferred.isDeferred(obj) //=> boolean

Parameters

obj : *
Object to determine

Returns

boolean
Returns true if an argument is Deferred.

Deferred.loop(n, fun) //=> Deferred

Parameters

n : (number|{begin:number|end:number|step:number})
Loop count or definition object
fun : function(number):*
Loop function

Returns

Deferred Called when all loop was completed
`loop` function provides browser-non-blocking loop. This loop is slow but not stop browser's appearance. This function waits a deferred returned by loop function.
  //=> loop 1 to 100
  loop({begin:1, end:100, step:10}, function (n, o) {
      for (var i = 0; i < o.step; i++) {
          log(n+i);
      }
  });
  //=> loop 10 times with sleeping 1 sec in each loop.
  loop(10, function (n) {
      log(n);
      return wait(1);
  });

Deferred.next(fun) //=> Deferred

Parameters

fun : function():*
Callback function

Returns

Deferred
`next` is shorthand for creating new deferred which is called after current queue.

Deferred.parallel(dl) //=> Deferred

Parameters

dl : (Array.<Deferred>|Object.<string|Deferred>)
Deferred objects wanted to wait

Returns

Deferred
`parallel` wraps up `deferredlist` to one deferred. This is useful when some asynchronous resources are required. `deferredlist` can be Array or Object (Hash). If you specify multiple objects as arguments, then they are wrapped into an Array.
  parallel([
      $.get("foo.html"),
      $.get("bar.html")
  ]).next(function (values) {
      values[0] //=> foo.html data
      values[1] //=> bar.html data
  });

  parallel({
      foo: $.get("foo.html"),
      bar: $.get("bar.html")
  }).next(function (values) {
      values.foo //=> foo.html data
      values.bar //=> bar.html data
  });

Deferred.register(name, fun)

Parameters

name : string
Name of method
fun : function(*):Deferred
Actual function of method
Register `fun` to Deferred prototype for method chain.
  // Deferred.register("loop", loop);

  // Global Deferred function
  loop(10, function (n) {
      print(n);
  }).
  // Registered Deferred.prototype.loop
  loop(10, function (n) {
      print(n);
  });

Deferred.repeat(n, fun) //=> Deferred

Parameters

n : number
Loop count
fun : function(number)
Loop function

Returns

Deferred Called when all loop was completed
Loop `n` times with `fun`. This function automatically returns UI-control to browser, if the loop spends over 20msec. This is useful for huge loop not to block browser UI. This function can't wait a deferred returned by loop function, compared with Deferred.loop.
  repeat(10, function (i) {
      i //=> 0,1,2,3,4,5,6,7,8,9
  });

Deferred.retry(retryCount, funcDeferred, options) //=> Deferred

Parameters

retryCount : number
Count number to retry
funcDeferred : function(number):Deferred
A function returns Deferred
options : {wait:number}
Options

Returns

Deferred
Try func (returns Deferred) till it finish without exceptions.
  Deferred.retry(3, function () {
      return http.get(...);
  }).
  next(function (res) {
      res //=> response if succeeded
  }).
  error(function (e) {
      e //=> error if all try failed
  });

Deferred.wait(sec) //=> Deferred

Parameters

sec : number
Second to wait

Returns

Deferred
`wait` returns deferred that will be called after `sec` elapsed with real elapsed time (msec)
  wait(1).next(function (elapsed) {
      log(elapsed); //=> may be 990-1100
  });