JSDeferredとは?
JSDeferredはcho45さんがモチキのDeferred機構に影響されて作ったらしいJavascript用の非同期処理ライブラリで、煩雑になりがちな複数の非同期処理間の協調動作を、簡単かつ柔軟に記述できるステキングなライブラリ
引用:http://unsigned.g.hatena.ne.jp/Trapezoid/20080425/1209054401
desu。
非同期処理
そもそも非同期処理とはどのようなものかといいますと、XHRリクエストがそのひとつです。
この例では、1,2,3の順に処理が実行されます。なれればなんてことないですが、処理順序が逆転していることがわかります。
1 2 3 4 5 | console.log("1"); var myAjax = new Ajax.Request(url, { method: 'get', onComplete: function(res){ console.log("3");}}); console.log("2"); |
もうすこし複雑な例。
1 2 3 4 5 6 7 8 9 10 11 12 13 | new Ajax.Request(url, { method: 'get', onComplete: function(res){ console.log(res); new Ajax.Request(url2,{ method: 'get', onComplete:function(res2){ console.log(res2); } }); } }); |
うーん、もう処理順序がぐちゃぐちゃで処理を追いづらいですね。。
JSDeferredをつかうと。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ajax_request(url). next(function(res){ console.log(res); }).ajax_request(url2). next(function(res2){ console.log(res2); }); vaf ajax_request = function(url){ var d=new Deferred(); new Ajax.Request(url,{ method: 'get', onComplete:function(res){ d.call(res); } }); return d; } Deferred.register('ajax_request',ajax_request); |
だいたいこんな感じに書けます。(直接ここに書いたので間違ってるかもしれません^^;)
ちゃんと上から順に実行されていくので、処理の流れを理解しやすいですね!
しくみ
ソースよんでくらはいw
短いですが、javascriptのエッセンスがつまっていてとても勉強になると思います。
参考:
http://d.hatena.ne.jp/amachang/20060910/1157911122
http://labs.gmo.jp/blog/ku/2007/09/firefoxsettimeout.html
http://ido.nu/kuma/2007/11/29/coding-synchronized-asynchronous-processing-intuitively-with-mochikit-async-deferred/
http://d.hatena.ne.jp/amachang/20080303/1204544340
http://d.hatena.ne.jp/amachang/20061129/1164799871
タグ: javascript, プログラム