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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
howdy39
June 15, 2018
Programming
1
400
Promise
howdy39
June 15, 2018
Tweet
Share
More Decks by howdy39
See All by howdy39
Slackbot × RAG で実現する社内情報検索の最適化
howdy39
2
620
AI新時代 情シスが向き合うべきAI活用戦略
howdy39
0
200
GAS x スプレッドシート x Looker Studio を組み合わせたデバイス管理 / DeviceMangent with GAS, SpreadSheet, Looker Studio
howdy39
3
1.7k
ChatGPTを使った 社内アシスタントBOTを作りました / ChatGPT Assistant Bot
howdy39
0
750
WebPagetestで始めるパフォーマンス計測 / Performance measurement starting with WebPagetest
howdy39
4
720
Storybookを用いたVue.js共通コンポーネント開発との戦い / stores-fights-storybook
howdy39
5
8.8k
gas-webpagetestで パフォーマンス計測を始めよう / get-started-measuring-performance-with-gas-webpagetest
howdy39
0
2.5k
カラーユニバーサルデザイン / color universal design
howdy39
0
990
Geolocation API
howdy39
0
120
Other Decks in Programming
See All in Programming
AIで開発はどれくらい加速したのか?AIエージェントによるコード生成を、現場の評価と研究開発の評価の両面からdeep diveしてみる
daisuketakeda
1
930
humanlayerのブログから学ぶ、良いCLAUDE.mdの書き方
tsukamoto1783
0
160
Vibe Coding - AI 驅動的軟體開發
mickyp100
0
160
AI Agent Dojo #4: watsonx Orchestrate ADK体験
oniak3ibm
PRO
0
140
ELYZA_Findy AI Engineering Summit登壇資料_AIコーディング時代に「ちゃんと」やること_toB LLMプロダクト開発舞台裏_20251216
elyza
2
1.3k
フロントエンド開発の勘所 -複数事業を経験して見えた判断軸の違い-
heimusu
7
2.7k
HTTPプロトコル正しく理解していますか? 〜かわいい猫と共に学ぼう。ฅ^•ω•^ฅ ニャ〜
hekuchan
2
670
OSSとなったswift-buildで Xcodeのビルドを差し替えられるため 自分でXcodeを直せる時代になっている ダイアモンド問題編
yimajo
3
580
Apache Iceberg V3 and migration to V3
tomtanaka
0
120
MUSUBIXとは
nahisaho
0
110
Unicodeどうしてる? PHPから見たUnicode対応と他言語での対応についてのお伺い
youkidearitai
PRO
1
1k
AI前提で考えるiOSアプリのモダナイズ設計
yuukiw00w
0
220
Featured
See All Featured
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
0
210
We Analyzed 250 Million AI Search Results: Here's What I Found
joshbly
1
600
The Mindset for Success: Future Career Progression
greggifford
PRO
0
230
Getting science done with accelerated Python computing platforms
jacobtomlinson
1
110
GraphQLとの向き合い方2022年版
quramy
50
14k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
190
Everyday Curiosity
cassininazir
0
120
How to Ace a Technical Interview
jacobian
281
24k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
1
45
jQuery: Nuts, Bolts and Bling
dougneiner
65
8.4k
Amusing Abliteration
ianozsvald
0
91
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.8k
Transcript
Promise 2018/06/15 第9回 TG社フロントエンド勉強会 Tatsuya Nakano(howdy39)
Promise • PromiseはJavaScriptのオブジェクト • 処理が終わったら教えるよという 約束 • 非同期処理を統一されたインターフェースで書ける • コールバック地獄の回避につかえる
• ES2015で追加 https://caniuse.com/#search=promise IE以外は使える・・・ →IEに対応するなら 要 Polyfill (es6-promise etc
Promiseの基本
Promiseの基本 // Promiseオブジェクトを作成 const promise = new Promise((resolve, reject) =>
{ // 何らかの処理(非同期処理) if (解決時) { resolve('解決'); } else { reject(new Error('棄却')); } });
Promiseの基本 const promise = new Promise((resolve, reject) => { /*
省略 */ }); // Promiseオブジェクトの結果により処理を実行 promise .then(value => { console.log('then', value); // resolve()が呼ばれた場合 }) .catch(value => { console.log('catch', value); // reject()が呼ばれた場合 });
Promiseオブジェクトの作り方 その1
new Promise(fn) const promise = new Promise((resolve, reject) => {
// 何らかの処理 });
Promiseオブジェクトの作り方 その2
Promise.resolve() Promise.resolve()は解決したPromiseオブジェクトを返す ※次の1と2は同じ 1. const promise = Promise.resolve('howdy39'); 2. const
promise = new Promise((resolve) => { resolve('howdy39') });
Promise.reject() Promise.reject()は棄却したPromiseオブジェクトを返す ※次の1と2は同じ 1. const promise = Promise.reject('howdy39'); 2. const
promise = new Promise((resolve, reject) => { reject('howdy39') });
Promiseオブジェクトの作り方 その3
Fetch 等のPromiseを返す関数など const promise = fetch('https://api.github.com/orgs/topgate');
Promiseオブジェクトが持つメソッド
Promiseオブジェクトが持つ2つのメソッド Promise#then(onFulfilled, onRejected) 解決時はonFulfilledハンドラの処理が呼ばれる 棄却時はonRejectedハンドラの処理が呼ばれる Promise#catch(onRejected) Promise#then(undefined, onRejected) のシンタックスシュ ガー
then()もcatch()、どちらもPromiseオブジェクトを返す
メソッドチェーン
メソッドチェーン Promiseはthenメソッドを使ってメソッドチェーンにできる ※thenメソッドの戻りがPromiseオブジェクトだから Promise.resolve() // 解決したPromise .then(() => console.log('aaa')) .then(()
=> console.log('bbb')) .then(() => console.log('ccc'));
次のPromiseに値を渡す(値をreturn) Promise.resolve() .then(() => { console.log('aaa'); return 'howdy39'; // 値をreturnすればOK
}) .then((value) => console.log('bbb', value)) .then(() => console.log('ccc'));
次のPromiseに値を渡す(Promiseをreturn) Promise.resolve() .then(() => { console.log('aaa'); return Promise.resolve('howdy39'); // Promiseをreturn
}) .then((value) => console.log('bbb', value)) .then(() => console.log('ccc'));
次のPromiseに値を渡す(fetchをreturn) Promise.resolve() .then(() => { console.log('aaa'); return fetch('https://api.github.com/orgs/topgate'); }) .then(response
=> { console.log('bbb'); return response.json(); // Response#json()はPromiseを返す }) .then(json => console.log('ccc', json));
棄却時のハンドリング
catch()で棄却をハンドリング Promiseはcatchメソッドを使って棄却時のハンドリングをする Promise.reject(new Error('my error')) // 棄却したPromise .then(() => console.log('aaa'))
.then(() => console.log('bbb')) .catch((error) => console.log('ccc', error)) .then(() => console.log('ddd'));
複数のPromiseを扱う
Promise.all()
Promise.all() Promiseの配列を指定すると並列に実行される すべてのPromiseが解決するとthenの処理が呼ばれる いずれかのPromiseが棄却するとcatchの処理が呼ばれる Promise.all([Promise1, Promise2, Promise3]);
Promise.all([ new Promise(resolve => { console.log('aaa'); resolve(); }), new Promise(resolve
=> { console.log('bbb'); resolve(); }), ]).then( () => console.log('ccc'), // 解決時の処理 ).catch( (error) => console.log('ddd', error) // 棄却時の処理; );
Promise.all()で複数の値を受け取る
分割代入を使うと楽 Promise.all([ Promise.resolve('aaa'), Promise.resolve('bbb'), Promise.resolve('ccc'), ]).then(values => { const [a,
b, c] = values; console.log('a', a); console.log('b', b); console.log('c', c); });
いずれかのPromiseが棄却
Promise.race()
Promise.race() Promiseの配列を指定すると並列に実行される いずれかのPromiseが解決するとthenの処理が呼ばれる いずれかのPromiseが棄却するとcatchの処理が呼ばれる Promise.race([Promise1, Promise2, Promise3]); 使う機会はあんまりなさそう
Promise.race([ new Promise(resolve => { console.log('aaa'); resolve(); }), new Promise(resolve
=> { console.log('bbb'); reject(new Error('bbb error')); }), ]).then( () => console.log('ccc'), // 解決時の処理 ).catch( (error) => console.log('ddd', error) // 棄却時の処理; );
おまけ
Promise#finally() Promiseオブジェクトにはthenとcatchの他にfinallyも存在 ES 2018 で実装 http://kangax.github.io/compat-table/es2016plus/#test-Promis e.prototype.finally
finallyは解決/棄却に関係なく呼ばれる Promise.resolve() .then(() => Promise.reject(new Error('my error'))) .catch(error => console.log('error',
error)) .finally(() => console.log('finally222'));
まとめ 1. Promiseを使うと非同期処理がきれいに書ける 2. fetch はPromiseを返す 3. Promise#all()で非同期処理をまとめてかける
参考 JavaScript Promiseの本 http://azu.github.io/promises-book Promise | MDN https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise Promise.prototype |
MDN https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype 今更だけどPromise入門 https://qiita.com/koki_cheese/items/c559da338a3d307c9d88 JavaScript の Promise https://developers.google.com/web/fundamentals/primers/promises