hachioji.pm #40 : asynchronous in JS

7
asynchronous Hachioji.pm #40

Transcript of hachioji.pm #40 : asynchronous in JS

Page 1: hachioji.pm #40 : asynchronous in JS

asynchronousHachioji.pm #40

Page 2: hachioji.pm #40 : asynchronous in JS

Introduce

川嶋 光太郎!

kkotaro0111!

ウェブデザイナ / フロントエンドエンジニア!

JavaScriptは⽣生が好きです

Page 3: hachioji.pm #40 : asynchronous in JS

Asynchronous in JSAjax!

jQuery.ajax({ url: “....”, success: function( data, status, xhr ){ // synchronous code... }, complete: function( xhr, status){ }, error: function( xhr, status, err ){ } });!

setTimeout/setInterval!

requestAnimationFrame!

other events...

Page 4: hachioji.pm #40 : asynchronous in JS

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

Page 5: hachioji.pm #40 : asynchronous in JS

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”); } }

Page 6: hachioji.pm #40 : asynchronous in JS

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...”); });

Page 7: hachioji.pm #40 : asynchronous in JS

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(){...});