hachioji.pm #40 : asynchronous in JS

316 views
267 views

Published on

Published in: Engineering, Technology, Design
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
316
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
1
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

hachioji.pm #40 : asynchronous in JS

  1. 1. asynchronous Hachioji.pm #40
  2. 2. Introduce 川嶋 光太郎! kkotaro0111! ウェブデザイナ / フロントエンドエンジニア! JavaScriptは⽣生が好きです
  3. 3. Asynchronous in JS Ajax! jQuery.ajax({
 url: “....”,
 success: function( data, status, xhr ){
 // synchronous code...
 },
 complete: function( xhr, status){ },
 error: function( xhr, status, err ){ }
 });! setTimeout/setInterval! requestAnimationFrame! other events...
  4. 4. Other way... Use “jQuery Deferred Object”! $.ajax return PROMISE object.! jQuery.ajax({ ... }).done(function( data, status, xhr ){ ... } );! jQuery.ajax({ ... }).fail(function(xhr, status, err ){ ... });! jQuery.then({ ... }).then(
 function( data, status, xhr){ ... }, // same done
 function( xhr, status, err) { ... }); // same fail
  5. 5. How to write code when we have multiple async-func. That’s this?! var callingtimes = 3;
 $.ajax({success: function(){ callingtimes -= 1; check();});
 $.ajax({success: function(){ callingtimes -= 1; check();});
 $.ajax({success: function(){ callingtimes -= 1; check();});
 function check(){
 if(callingtimes === 0){ console.log(“complete”); }
 }
  6. 6. No, $.when is perfect. That’s this!! var p1 = $.ajax({});
 var p2 = $.ajax({});
 var p3 = $.ajax({});
 
 $.when( p1, p2, p3 ).done(function(){
 console.log(“complete”);
 }).fail(function(){ console.log(“so bad...”); });
  7. 7. I don’t know how many times to call... That’s right.! var times = (Math.random() * 10) | 0;
 var p_ary = [];
 for(var i = 0; i < times; i++){
 var p = $.ajax({});
 p_ary.push( p );
 }
 
 $.when.apply(null, p_ary).done(function(){...});


×