Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
非同期プログラミングPromiseに入門
Search
Yohei Munesada
August 27, 2015
Technology
0
1.3k
非同期プログラミングPromiseに入門
JavaScriptの非同期プログラミングの手法の一つ、Promiseを説明したスライド。HTML5ビギナーズの第12回の登壇内容です。
Yohei Munesada
August 27, 2015
Tweet
Share
More Decks by Yohei Munesada
See All by Yohei Munesada
G'sデータベース設計の講義
yoheimune
4
5.2k
How to create a service, How to google !
yoheimune
0
280
Machine Learning Basic and Python
yoheimune
1
470
Python Scraping and Web Apps for G's ACADEMY TOKYO
yoheimune
0
220
DevelopWorkflow and Solving Problems
yoheimune
0
420
Git and Github for Beginners
yoheimune
1
270
Data Science BOOTCAMP Practices - Recommendation
yoheimune
0
180
Data Science BOOTCAMP Practices
yoheimune
0
340
Machine Learning with Python
yoheimune
0
310
Other Decks in Technology
See All in Technology
DUSt3R, MASt3R, MASt3R-SfM にみる3D基盤モデル
spatial_ai_network
2
110
Snykで始めるセキュリティ担当者とSREと開発者が楽になる脆弱性対応 / Getting started with Snyk Vulnerability Response
yamaguchitk333
2
180
AWS re:Invent 2024で発表された コードを書く開発者向け機能について
maruto
0
190
サーバレスアプリ開発者向けアップデートをキャッチアップしてきた #AWSreInvent #regrowth_fuk
drumnistnakano
0
190
ゼロから創る横断SREチーム 挑戦と進化の軌跡
rvirus0817
2
270
終了の危機にあった15年続くWebサービスを全力で存続させる - phpcon2024
yositosi
8
7.6k
KnowledgeBaseDocuments APIでベクトルインデックス管理を自動化する
iidaxs
1
260
How to be an AWS Community Builder | 君もAWS Community Builderになろう!〜2024 冬 CB募集直前対策編?!〜
coosuke
PRO
2
2.8k
PHP ユーザのための OpenTelemetry 入門 / phpcon2024-opentelemetry
shin1x1
1
200
WACATE2024冬セッション資料(ユーザビリティ)
scarletplover
0
200
社内イベント管理システムを1週間でAKSからACAに移行した話し
shingo_kawahara
0
180
10分で学ぶKubernetesコンテナセキュリティ/10min-k8s-container-sec
mochizuki875
3
330
Featured
See All Featured
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
6
520
GraphQLとの向き合い方2022年版
quramy
44
13k
Unsuck your backbone
ammeep
669
57k
How STYLIGHT went responsive
nonsquared
95
5.2k
Git: the NoSQL Database
bkeepers
PRO
427
64k
Side Projects
sachag
452
42k
Raft: Consensus for Rubyists
vanstee
137
6.7k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
365
25k
Producing Creativity
orderedlist
PRO
341
39k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
Building Flexible Design Systems
yeseniaperezcruz
327
38k
Site-Speed That Sticks
csswizardry
2
190
Transcript
࣍ੈඇಉظϓϩάϥϛϯά Promise Yohei Munesada
फఆ༸ฏ 5XJUUFS!ZPIFJ.VOF #MPHIUUQXXXZPIFJNOFU
ಡॻͷ͓࣌ؒͰ͢CZ"NFCB
ࠓ Promise Λѻ͍·͢
ϏΪφʔͷϙΠϯτ 1SPNJTFͷ༰Λཧղ͍ͯ͠Δ 1SPNJTFΛ༻͍ͨ࠷৽༷͕ಡΊΔ K2VFSZ%FGFSSFEΛ༻͍ͨ1SPNJTFϓϩάϥϛϯά͕Ͱ͖Δ
ϏΪφʔͷϙΠϯτ 1SPNJTFͷ༰Λཧղ͍ͯ͠Δ 1SPNJTFΛ༻͍ͨ࠷৽༷͕ಡΊΔ K2VFSZ%FGFSSFEΛ༻͍ͨ1SPNJTFϓϩάϥϛϯά͕Ͱ͖Δ 1SPNJTFʹΑΔඇಉظϓϩάϥϛϯά͕ॻ͚ΔಡΊΔ
Let’s Start!!
Promise ͬͯͳʹʁ
Promise ඇಉظϓϩάϥϛϯάͷΓํ
$BMMCBDLͰඇಉظϓϩάϥϛϯά doAsync1(function (v1) { doAsync2(function (v2) { doAsync3(function (v3) {
doAsync4(function (v4) { console.debug(v4); }); }); }); });
1SPNJTFͰඇಉظϓϩάϥϛϯά doAsync1() .then(doAsync2) .then(doAsync3) .then(doAsync4) .then(function (v4) { console.debug(v4); });
doAsync1(function(v1){ doAsync2(function(v2){ doAsync3(function(v3){ doAsync4(function(v4){ console.debug(v4); }); }); }); }); doAsync1()
.then(doAsync2) .then(doAsync3) .then(doAsync4) .then(function(v4){ console.debug(v4); }); 1SPNJTFͷ߹ $BMMCBDLͷ߹
1SPNJTFͷར 㾎 ඇಉظϓϩάϥϛϯάͷ৽͍͠ॻ͖ํ 㾎 Τϥʔॲཧ͕͍͍ײ͡ʹॻ͚Δʢޙड़ʣ 㾎 ύϥϨϧॲཧ͍͍ײ͡ʹॻ͚Δʢޙड़ʣ 㾎 ඇಉظॲཧ͕࣮ߦࡁ͔൱͔ؾʹ͠ͳͯ͘ྑ͍ʢޙड़ʣ
Promise ʙجૅฤʙ
// Promiseͷ࡞ var p = new Promise(function (resolve, reject) {});
// ޭ࣌ͷॲཧ p.then(function (value) {}); // ࣦഊ࣌ͷॲཧ p.catch(function (reason) {}); ֓ཁͭͷίʔυ
Pending Resolved Rejected ҙ ্༷GVMpMMFE SFKFDUFE QFOEJOH TFUUMFEͰ͕͢ɺ͔Γ͘͢ݴ͍͑Λ͍ͯ͠·͢ɻ ·ͩޭࣦഊ͍ͯ͠ͳ͍ ޭͨ͠
ࣦഊͨ͠ ֓ཁͭͷঢ়ଶ
Pending Resolved Rejected ҙ ্༷GVMpMMFE SFKFDUFE QFOEJOH TFUUMFEͰ͕͢ɺ͔Γ͘͢ݴ͍͑Λ͍ͯ͠·͢ɻ ·ͩޭࣦഊ͍ͯ͠ͳ͍ ޭͨ͠
ࣦഊͨ͠ ֓ཁͭͷঢ়ଶ
Pending Resolved Rejected ҙ ্༷GVMpMMFE SFKFDUFE QFOEJOH TFUUMFEͰ͕͢ɺ͔Γ͘͢ݴ͍͑Λ͍ͯ͠·͢ɻ ·ͩޭࣦഊ͍ͯ͠ͳ͍ ޭͨ͠
ࣦഊͨ͠ ֓ཁͭͷঢ়ଶ
Pending Resolved Rejected ҙ ্༷GVMpMMFE SFKFDUFE QFOEJOH TFUUMFEͰ͕͢ɺ͔Γ͘͢ݴ͍͑Λ͍ͯ͠·͢ɻ ·ͩޭࣦഊ͍ͯ͠ͳ͍ ޭͨ͠
ࣦഊͨ͠ ֓ཁͭͷঢ়ଶ
var p = new Promise(function (resolve, reject) { // Կ͍ͯ͠ͳ͍
}); Pending
// resolveͰޭ var p = new Promise(function (resolve, reject) {
resolve(1); }); // ޭͨ͠Βthen͕ݺΕΔ p.then(function (value) { console.log(value); // 1 }); Pending => Resolved
Pending => Rejected // rejectͰࣦഊ var p = new Promise(function
(resolve, reject) { rejected(‘error is occurred’); }); // ࣦഊͨ͠Βcatch͕ݺΕΔ p.catch(function (error) { console.log(error); // ‘error is occurred’ });
var p = new Promise(function (resolve, reject) { var img
= new Image(); img.src = ‘./rss.png'; img.onload = function () {resolve(this);} image.onerror = function () {reject('fail');} }); p.then(function (image) { console.debug(image); }); p.catch(function (reason) { console.debug(reason); }); ࣮ફαϯϓϧ
Promise ʙجૅฤᶄʙ
UIFOνΣʔϯͰ͖Δ doAsync1() .then(doAsync2) .then(doAsync3) .then(doAsync4) .then(function(v4){ console.debug(v4); });
get(‘./book.json’) .then(function (responseText) { return JSON.parse(responseText); }).then(function (book) { console.log(‘book
is JSON!!!’, book); }); UIFOνΣʔϯͰ͖ΔᶃΛฦ٫͢Δ
getJson(‘./book.json’).then(function (book) { return new Promise (function (resolve, reject) {
var image = new Image(); image.src = book.imageUrl; image.onload = function () {resolve(this)}; }); }).then (function (image) { console.log(‘image:’, image); }); UIFOνΣʔϯͰ͖Δᶄ1SPNJTFΛฦ٫͢Δ
Promise ʙԠ༻ฤᶃʙ
1SPNJTFͷར 㾎 ඇಉظϓϩάϥϛϯάͷ৽͍͠ॻ͖ํ 㾎 Τϥʔॲཧ͕͍͍ײ͡ʹॻ͚Δʢޙड़ʣ 㾎 ύϥϨϧॲཧ͍͍ײ͡ʹॻ͚Δʢޙड़ʣ 㾎 ඇಉظॲཧ͕࣮ߦࡁ͔൱͔ؾʹ͠ͳͯ͘ྑ͍ʢޙड़ʣ
ᶃ՚ྷͳΤϥʔϋϯυϦϯά$BMMCBDLฤ doAsync1 (function (result) { doAsync2 (function (result) { doAsync3
(function (result) { finishAction(); }); }); });
ᶃ՚ྷͳΤϥʔϋϯυϦϯά$BMMCBDLฤ doAsync1 (function (result) { if (isError(result)) treatError(); doAsync2 (function
(result) { if (isError(result)) treatError(); doAsync3 (function (result) { if (isError(result)) treatError(); finishAction(); }); }); }); Τϥʔॲཧ Τϥʔॲཧ Τϥʔॲཧ
ᶃ՚ྷͳΤϥʔϋϯυϦϯά1SPNJTFฤ doAsync1() .then(doAsync2) .then(doAsync3) .then(finishAction) .catch(treatError); // doAsync1ͳͲ͕PromiseΛฦ͢Α͏ʹ࣮͢Ε // ্هͷΑ͏ʹγϯϓϧʹͳΓ
// Τϥʔॲཧ࠷ޙʹ1ͭॻ͚ͩ͘Ͱྑ͘ͳΔ
ᶄ՚ྷͳύϥϨϧॲཧ$BMMCBDLฤ doAsync1 doAsync2 finishAction EP"TZODͷॲཧΛ͔ͬͯΒɺ pOJTI"DUJPOΛݺͿ
ᶄ՚ྷͳύϥϨϧॲཧ$BMMCBDLฤ var results =[], numOfAction = 2; doAsync1 (function (result)
{ results.push(result); if (results.length === numOfAction) finishAction(); }); doAsync2 (function (result) { results.push(result); if (results.length === numOfAction) finishAction(); });
ᶄ՚ྷͳύϥϨϧॲཧ1SPNJTFฤ Promise .all([doAsync1(), doAsync2()] .then(finishAction); // doAsync1ͱdoAsync2ΛPromise࣮ʹͯ͠ //ʮPromise.allʯΛ༻͍Δ͜ͱͰ // ෳͷPromiseͷύϥϨϧ࣮ߦͱ
// ͦͷޙͷྃॲཧΛ៉ྷʹهड़͢Δ͜ͱ͕Ͱ͖Δ
ᶅ͍ͭͰݺͼग़͠Մೳ$BMMCBDLฤ var img = document.querySelector('img'); img.onload = function () {
finishAction(this); } if (img.complete) { finishAction(this); } // ը૾ͷಡΈࠐΈঢ়گʹ߹Θͤͨ // ࣮Λ͢Δඞཁ͕͋Γେมɾɾɾ
ᶅ͍ͭͰݺͼग़͠Մೳ1SPNJTFฤ // ʢԾͷʣimageཁૉ͕ready()ͰPromiseΛฦͤ var img = document.querySelector('img'); img.ready().then(finishAction); // Image͕ϩʔυલɺϩʔυޙؔͳ͘
// thenΛίʔϧ͢Εϩʔυࡁͷը૾Λऔಘ͢Δ // ͜ͱ͕Ͱָ͖ͯνϯ♪
ϏΪφʔͷϙΠϯτ ʢࡁʣ1SPNJTFͷ༰Λཧղ͍ͯ͠Δ 1SPNJTFΛ༻͍ͨ࠷৽༷͕ಡΊΔ K2VFSZ%FGFSSFEΛ༻͍ͨ1SPNJTFϓϩάϥϛϯά͕Ͱ͖Δ
࠷৽༷Λ͖ݟʂʂ Service Worker
1VTI௨4FSWJDF8PSLFS navigator.serviceWorker.ready().then(function (reg) { reg.pushManager.subscribe({ userVisibleOnly: true }).then(function (subscription) {
console.debug(‘success!!’); }); });
1VTI௨4FSWJDF8PSLFS navigator.serviceWorker.ready().then(function (reg) { reg.pushManager.subscribe({ userVisibleOnly: true }).then(function (subscription) {
console.debug(‘success!!’); }); }); 1SPNJTF 1SPNJTF
IUUQTTQFBLFSEFDLDPNZPIFJNVOFQVTIOPUJpDBUJPOJTDPNNJOH
IUUQTTQFBLFSEFDLDPNDIJOUSPEVDUJPOUP TFSWJDFXPSLFS ࢀߟ
ϏΪφʔͷϙΠϯτ ʢࡁʣ1SPNJTFͷ༰Λཧղ͍ͯ͠Δ ʢࡁʣ1SPNJTFΛ༻͍ͨ࠷৽༷͕ಡΊΔ K2VFSZ%FGFSSFEΛ༻͍ͨ1SPNJTFϓϩάϥϛϯά͕Ͱ͖Δ
jQuery.deferred
K2VFSZEFGFSSFEͰ1SPNJTFίʔσΟϯά // ޭ͢Δ߹ function doAsync () { var d =
new $.Deferred(); d.resolve(1); return d.promise(); } doAsync().then(function (value) { console.debug(value); // 1 });
K2VFSZEFGFSSFEͰ1SPNJTFίʔσΟϯά // ࣦഊ͢Δ߹ function doAsync () { var d =
new $.Deferred(); d.reject(‘something is strange’); return d.promise(); } doAsync().fail(function (reason) { console.debug(reason); //‘something is strange’ });
BKBYϑΝϛϦʔ%FGFSSFEΛฦ͢ $.getJSON('./book.json').then(function (book) { console.debug(book); });
XIFOͰύϥϨϧॲཧ $.when( $.getJSON('./book1.json'), $.getJSON(‘./book2.json’) ).then(function (result1, result2) { console.debug(result1[0]); //
book1 console.debug(result2[0]); // book2 });
ϏΪφʔͷϙΠϯτ ʢࡁʣ1SPNJTFͷ༰Λཧղ͍ͯ͠Δ ʢࡁʣ1SPNJTFΛ༻͍ͨ࠷৽༷͕ಡΊΔ ʢࡁʣK2VFSZ%FGFSSFEͰ1SPNJTFίʔσΟϯά
8FIBWF Promise 0IIIIIIIIIIIIIIII
ࢀߟ63-1SPNJTFؔ࿈ 㾎 +BWB4DSJQU1SPNJTFT5IFSFBOECBDLBHBJO)5.-3PDLT 㾎 1SPNJTF" ༷ΛνϡʔτϦΞϧܗࣜͰৄ͘͠ղઆ͠·͢:PIFJ./&5 㾎 1SPNJTFTϒϥβʔ+BWB4DSJQUͷ৽͍͠ඇಉظඪ४ʹͳΔ͔ʁ*OGP2 㾎 ࠓߋ͚ͩͲ1SPNJTFೖ2JJUB
㾎 ͡Ίͯͷ1SPNJTF2JJUB 㾎 +BWB4DSJQU1SPNJTFͷຊB[VHJUIVCJP 㾎 /PEFKTͷίʔϧόοΫࠈΛ1SPNJTF(FOFSBUPSΛͬͯղফ͢Δ1045% 㾎 1SPNJTF+BWB4DSJQUc.%/ 㾎 &$."4DSJQU-BOHVBHF4QFDJpDBUJPO&$."UI&EJUJPO
ࢀߟ63-K2VFSZEFGFSSFEؔ࿈ 㾎 രͰΘ͔ΔK2VFSZ%FGFSSFEೖ:BIPP+"1"/5FDI#MPH 㾎 ࠓ͞Βฉ͚ͳ͍K2VFSZ%FGFSSFEೖ2JJUB 㾎 K2VFSZEFGFSSFEͷ͍ํ$PEF(SJE 㾎 K2VFSZϞμϯ"KBYͳॻ͖ํΛࢦͯ͠)BDL:PVS%FTJHO 㾎
K2VFSZ%FGFSSFEΛָ͍ͬͯ͠ඇಉظੜ׆ΛૹΔํ๏2JJUB 㾎 +"7"4$3*15130.*4&4"/%8):+26&3:*.1-&.&/5"5*0/*4#30,&/
Thank you फఆ༸ฏ 5XJUUFS!ZPIFJ.VOF #MPHIUUQXXXZPIFJNOFU