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

Append future function #19

Description

@cho45
/**
 * 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);
    });
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions