先日からjQueryの非同期処理について少し勉強しはじめた者です。
調べていくうちにいろいろなパターンがあり混乱してしまい、少し整理できればと思いご質問させて頂きます。
どうぞお手柔らかに宜しくお願い致します。
以下すべてのコードはこちらに書いてあります。
https://jsfiddle.net/xdfvzo0n/
###基本的な関数
まず基本的な関数hoo()
をご用意しました。この呼び出し方についてのご質問になります。
function hoo(){ var deferred = $.Deferred(); setTimeout(function(){ console.log('2'); deferred.resolve(); },1000); return deferred.promise(); }
###ご質問➀
下記の【A】【B】はどちらも「1→2→3」と同じ結果になるのですが、何が違うでしょうか?
よく区別される使いどころなどの例を教えて頂きたく思います。
【A】
$('.buttonA').click(function(){ $.Deferred().resolve() .then(function(){ console.log('1'); }) .then(function() { return hoo(); }) .then(function() { console.log('3'); }); });
【B】
$('.buttonB').click(function(){ $.when( console.log('1') ) .then(function(){ return hoo(); }) .then(function() { console.log('3'); }); });
###ご質問➁
上の【B】は2つ目のthen()
でreturn
していますが、次の【C】はしていません。
なぜ【C】だと順番の処理ができないのでしょうか?
そして【B】のreturn
は、何を返していると考えればいいのでしょうか?
【C】
$('.buttonC').click(function(){ $.when( console.log('1') ) .then(function(){ hoo(); }) .then(function() { console.log('3'); }); });
###ご質問➂
上の【C】のconsole.log('1')
とhoo()
を入れ変えたのが次の【D】です。
なぜ【C】は順番の処理ができず【D】はできるのでしょうか?
そして【D】においては、【A】や【B】のようにreturn hoo()
と書かなくてもhoo()
だけでできるのはなぜでしょうか?(なぜwhen()
の中だとreturn
がいらず、then()
の中だと必要になるのでしょうか?)
【D】
$('.button3').click(function(){ $.when( hoo() ) .then(function(){ console.log('1') }) .then(function() { console.log('3'); }); });
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/24 18:16
2019/08/26 01:09
2019/08/26 01:25
2019/08/26 01:28