LoginSignup
1
0

More than 5 years have passed since last update.

Chain method

Posted at

This code snipet gives flow controling to you for callback chain.

(function (global, doc) {

    /**
    * Chain callbacks.
    * @param {Function[]} [No arguments name] Call function objects as chain method.
    * @return undefined
    * @example
    *   chain(function (next) {... next(); }, function (next) {... next(); }, function (next) {... next(); }...);
    *       -> next is callback.
    */
    function chain() {

        var actors = Array.prototype.slice.call(arguments);

        function next() {

            var actor = actors.shift(),
                arg = Array.prototype.slice.call(arguments);

            //push `next` method to argumetns to last.
            arg.push(next);

            //when `actor` is function, call it.
            (Object.prototype.toString.call(actor) === '[object Function]') && actor.apply(actor, arg);
        }

        next();
    }

    /* -----------------------------------------------
       EXPORT
    -------------------------------------------------- */
    global.chain = chain;
}(this, document));
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