Serialize asynchronous methods

by __gfx__
非同期メソッドを直列化するコード
♥0 | Line 56 | Modified 2012-02-16 23:37:06 | MIT License
play

ActionScript3 source code

/**
 * Copyright __gfx__ ( http://wonderfl.net/user/__gfx__ )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/psjF
 */

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.utils.setTimeout;
    
    public class AsyncExample extends Sprite
    {
        private var text :TextField;
        
        private function puts(s :String) :void {
            text.appendText(s + "\n");
            trace(s);
        }
        
        public function AsyncExample()
        {
            super();
            
            text = new TextField();
            text.x = 100;
            text.y = 0;
            text.scaleX = 3.0;
            text.scaleY = 3.0;
            addChild(text);
            
            var tasks :Vector.<Function> = new Vector.<Function>();
        
            var next :Function = function() :void {
                var task :Function = tasks.shift();
                if(task !== null) {
                    task();
                }
            };
            
            tasks.push(function() :void {
                setTimeout(function() :void {
                    puts('one');
                    
                    next();
                }, 1000);
            });
            tasks.push(function() :void {
                setTimeout(function() :void {
                    puts('two');
                    
                    next();
                }, 100);
            });
            tasks.push(function() :void {
                setTimeout(function() :void {
                    puts('three');
                    
                    next();
                }, 1000);
            });
            tasks.push(function() :void {
                setTimeout(function() :void {
                    puts('four');
                    
                    next();
                }, 100);
            });
                
            next();
        }
    }
}