LoginSignup
2
3

More than 5 years have passed since last update.

yield で async/await 的な何か

Posted at

実験用に「指定ミリ秒後に resolve される Deferred (というか Promise)」を返してくれる delay 関数を作っておく。ついでに resolve 結果として連番が返ってくるようにしておく。

var i = 0;

function delay(ms){
    var d = jQuery.Deferred();
    setTimeout(function(){
        d.resolve(i++);
    }, ms);
    return d.promise();
}

で、何がしたいかというと C# の async/await もしくは F# のコンピューテーション式よろしく、非同期タスクを同期的に書きたい。

async(function(){

    var x = yield delay(1000);
    console.log(x);
    x = yield delay(1000);
    console.log(x);
});

こんな感じ。

これをやるために用意する async 関数が下のようになる。

function async(action){

    var iterator = action();
    var promise = iterator.next();

    if (promise) {
        promise.done(next);
    }

    function next(result){
        promise = iterator.send(result);
        if (promise) {
            promise.done(next);
        }
    }
}

これ、Internet Explorer でまともに動くようになれば Web アプリでのメッセージボックス表示とかがコーディングしやすくなるんだけどなぁ。

2
3
1

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
2
3