最近「JSDeferred、JSDeferred」言い過ぎている感があるし、さらに今更感満載なのだけれども、自分のJavaScriptの書き方を変えたものであることは確かなので、今しばらく「JSDeferred、JSDeferred」言っていこうと思う。
JSDeferredの可読性
Deferred .next(function(){ two(); //2 return '2'; }) .next(function(x){ alert(x);//>2 three(); //3 }); one(); //1
と書けば同期的に処理できる。値の受け渡しも楽。
"next()"というのも「次」という感じでわかりやすい。
Deferred .next(function(){ two(); //2 }) .wait(0) .next(function({ three(); //3 }); one(); //1
なんて書けば、two()とthree()は処理を離すこともできる。
さらに、
Deferred .next(function(){ return $.ajax({ type:'GET', url:'/hoge', success:function(res){//<'hoge' return res; } }); //2 }) .next(function(res){ alert(res);//>'hoge' three(); //3 }); one(); //1
JSDeferredのエラーハンドリング
多分これだけでもかなり有用なライブラリといえるんじゃないかと思う。
try{}catch{}が苦手な自分でもわかりやすく使いやすい。
Deferred .next(function(){ two(); //2 throw 'error'; }) .next(function(res){ three(); //スルー }) .error(function(e){ alert(e);//>'error' //3 }); one(); //1
みたいに例外を全てまとめることも可能。
とりあえず、まだまだ使いこなせていないのでCodeReadingを進めないと。