Upload
kotaro-kawashima
View
169
Download
3
Embed Size (px)
Citation preview
asynchronousHachioji.pm #40
Introduce
川嶋 光太郎!
kkotaro0111!
ウェブデザイナ / フロントエンドエンジニア!
JavaScriptは⽣生が好きです
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...
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
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”); } }
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...”); });
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(){...});