Skip to content
This repository has been archived by the owner on Jan 19, 2018. It is now read-only.

Append future function #19

Open
cho45 opened this issue Mar 16, 2012 · 0 comments
Open

Append future function #19

cho45 opened this issue Mar 16, 2012 · 0 comments

Comments

@cho45
Copy link
Owner

cho45 commented Mar 16, 2012

/**
 * Create future object
 *
 * @example
 *   var token = future(future () {
 *     return $.getJSON('/api/token').next(function (data) { return data.token });
 *   });
 *
 *   token.next(function (token) {
 *     alert(token);
 *   });
 *
 *   token.next(function (token) {
 *     console.log(token);
 *   });
 *
 *   token.next(function (token) {
 *     // Use token
 *   }).
 *   error(function (e) {
 *     alert(e);
 *   });
 *
 * Future is like Deferred object but it behaves as "future" value (deferred process and future value).
 * Actually, this object is for a recycling value of Deferred.
 *
 * @param {function():Deferred} function returns Deferred which has a value for recycling.
 * @return {{next:function()}} Future object is has only 'next' function which return Deferred object.
 */
function future (fun) {
    var d = fun();
    var state, value;
    var waiting = [];

    d.
        next(function (val) {
            state = "call";
            value = val;
        }).
        error(function (err) {
            state = "fail";
            value = err;
        }).
        next(function () {
            for (var i = 0, it; (it = waiting[i]); i++) {
                it[state](value);
            }
        });

    return {
        next : function (cb) { /* return new Deferred */
            var d = new Deferred();
            d.next(cb);
            if (state) {
                d[state](value);
            } else {
                waiting.push(d);
            }
            return d;
        }
    };
}


var val = future(function () {
    return Deferred.wait(0.5);
});

val.next(function (v) {
    console.log(v);
    val.next(function (v) {
        console.log(v);
    });
});
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant