LoginSignup
20
20

More than 5 years have passed since last update.

Deferred挫折したけど非同期をスマートに書きたい人へ

Posted at

=============================================

簡単&低機能なものを作りました。

使い方

chain()とnextだけ覚えて下さい

var img,img2;

chain( function( next ){
    img = new Image();
    img.onload = next;
    img.src = "http://dummyimage.com/600x400/000/fff";
})
.chain( function( next ){
    img2 = new Image();
    img2.onload = next;
    img2.src =  "http://dummyimage.com/600x400/000/fff";
})
.chain( function( next ){
    setTimeout( next, 1000 );
})
.chain( function( next ){
    console.log( "img,img2が読み込まれて1秒たった" );
});

ライブラリ

(function(){ 
    // TODO 綺麗にする
    var Chain = function(){
        this._func = arguments.length==1? arguments[0]: arguments[1];
        this._next = function(){};
        this._parent = arguments.length==1? null: arguments[0];
        if( this._parent ) return;
        setTimeout((function(){
            this._exec();
        }).bind(this),0);
    };
    Chain.prototype = {
        _exec: function(){
            this._func( (function(){ this._next(); }).bind(this) );
        },
        chain: function( func ){
            var chain = new Chain( this, func );
            this._next = function(){ chain._exec(); };
            return chain;
        }
    };
    window.chain = function( func ){ return new Chain(func); }
})();
20
20
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
20
20