SlideShare a Scribd company logo
1 of 16
Download to read offline
JavaScriptの非同期処理
合同会社FullSailing
横山 巧
目次
§1 JavaScriptの非同期処理
§1.1 コールバックについて
➢ イベントループ
➢ setTimeout()の例
§1.2 委譲(delegate)について
➢ イベントハンドラの登録
➢ Promiseの使用例
➢ Promiseの実装例
§1.3 async/awaitについて
➢ 糖衣構文(シンタックスシュガー)
参考文献
目次(再掲)
§1 JavaScriptの非同期処理
§1.1 コールバックについて
➢ イベントループ
➢ setTimeout()の例
§1.2 委譲(delegate)について
➢ イベントハンドラの登録
➢ Promiseの使用例
➢ Promiseの実装例
§1.3 async/awaitについて
➢ 糖衣構文(シンタックスシュガー)
参考文献
§1 JavaScriptの非同期処理
プログラムを、1行ずつ完了するまで待ちながら進める"同期処理"に対して...
待ち時間が発生するような処理(ファイルの読み書き、HTTP通信など)の完了を待たず、
続く行のプログラムを実行した後で結果を処理するテクニック。
➢ 未完了の行が発生しても、プログラムの実行を進める仕組み
➢ 未完了だった行の処理が完了した後に結果を処理する仕組み
が必要。
JavaScriptはシングルプロセス・シングルスレッドで動作するプログラミング言語。
⚠︎ 注意 : 非同期処理を実現するための仕組みは、必ずしも他のプログラミング言語と
同じでない!!
JavaScriptランタイムの動作原理を学び、非同期処理を支える言語機能を活用することで
理解を深めていく。
§1.1 コールバックについて
関数のうち、他の関数に引数として渡され、
任意の処理を実行するもの。
同期処理・非同期処理を問わず利用される。
非同期処理においては、完了後の結果を
処理するためのプログラムをコールバック
関数にまとめ、適切なタイミングで実行する。
コールバック関数が入れ子状に宣言されて
いくと、必要以上にネストの深いプログラムが
作成されること("コールバック地獄")がある。
できるだけ回避されるよう工夫する。
参考 : mdn web docs - Callback function
➢ イベントループ
JavaScriptランタイムは、マシンのメモリ上に
"メッセージキュー"(以下、キュー)を用意し、
関数と紐づいたデータを管理している。
➢ "スタック"と呼ばれる領域では、実行中の
関数の引数とローカル変数
➢ "ヒープ"と呼ばれる領域では、オブジェクト
が管理されている。
キューは常にループ処理で監視されており、
データが存在すると、FIFO(先入れ先出し)
方式で、紐づいた関数が実行されていく。
JavaScriptプログラムを実行するキューのループ制御を"イベントループ"と呼ぶ。
非同期処理においては、待ち状態の処理が完了したタイミングで、コールバック関数と
紐づいたメッセージがキューに追加され、既存のメッセージの後に処理される。
参考 : mdn web docs - The event loop
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)
➢ setTimeout()の例
非同期関数のひとつである"setTimeout()"を
使用して、イベントループの動作を確認する。
➢ setTimeout()を実行
➢ 第1引数 : コールバック関数
➢ 第2引数 : 遅延(0ミリ秒)
➢ whileループを1秒実行
setTimeout()に渡したコールバック関数は
即時メッセージキューに追加されるが、
whileループ以降の処理が完了するのを
待って実行される。
§1.2 委譲(delegate)ついて
関数の呼び出しを行うオブジェクトと、
実際に処理を行うオブジェクトとを
分離するテクニック。
IT用語辞典e-Words
たとえばイベント処理に応用できる。
コールバックと委譲(delegate)を
組み合わせることにより、JavaScriptの
非同期処理を実装する上で欠かせない、
"Promise"を模倣したオブジェクトを
作成することができる。
➢ イベントハンドラの登録
イベント発生時に、委譲(delegate)を用いて
登録されたハンドラを実行する。
➢ コントローラーオブジェクトに、
イベントハンドラを定義する
➢ ボタンオブジェクトに、クリック
イベント発生時のハンドラを
登録する
➢ イベント発生時、ボタンオブジェクトに
登録されたハンドラを順番に実行する
➢ Promiseの使用例
2つのコールバック関数(resolve/reject)を
引数に持つ関数を、コンストラクタに渡す。
Promiseをインスタンス化した後のプログラムで
"then"メソッドが呼び出されている場合...
➢ resolveメソッドは、"then"メソッドの第1引数に
渡されたコールバック関数を実行する
➢ rejectメソッドは、"then"メソッドの第2引数に
渡されたコールバック関数を実行する
"then"メソッドは連続的に呼び出すことができ、
直前の"then"メソッドのコールバック関数が
Promiseを返さない場合、返り値を引数として
第1引数に渡されたコールバック関数を実行する。
"コールバック地獄"の発生を防ぎ、非同期処理を
連続的に実行することができる。
➢ Promiseの実装例
非同期関数の実行が、コールバックによって
連鎖的に委譲(delegate)されるオブジェクトを
作成する。
➢ "then"メソッドは、Promiseインスタンスを
新たに生成する
このとき、successHandler/failureHandlerと、
新しいPromiseインスタンスのresolve/reject
メソッドとを、インスタンスプロパティに保存する
➢ "最初のPromise"は、コンストラクタに渡された
関数内でresolve/rejectメソッドが呼ばれると、
successHandler/failureHandlerを実行し、
"次のPromise"のresolve/rejectメソッドを
呼び出す
➢ "最後のPromise"のresolve/rejectメソッドが
呼び出されるまで同様の処理を繰り返す
参考 : さくらのナレッジ - JavaScriptの非同期処理を理解する その2 〜Promise編〜
§1.3 async/awaitについて
Promiseによる非同期処理の制御を、
"then"メソッドの連鎖的な呼び出しなしに、
同期処理に近い書式で記述する。
➢ 順番に実行したい非同期処理を、
"async"キーワードをつけた関数内に
まとめる
➢ "await"キーワードつけた処理は、
完了(resolve/reject)まで、
続く行の実行を待たせることができる
➢ resolveメソッドの引数に渡した値は、
変数に保存し、続く処理で使用できる
➢ rejectメソッドの引数に渡した値または
例外は、try/catch構文で補足できる
参考 : mdn web docs - async function
➢ 糖衣構文(シンタックスシュガー)
"async/await"は、Promiseを利用した
非同期処理を簡潔かつ同期処理に近い、
読みやすい形式で記述でき、糖衣構文の
性質を持っていると言える。
※厳密に糖衣構文であるとは断言しない。
"async"キーワードをつけて宣言された
関数を、Promiseを用いて模倣する。
➢ "await"キーワードにより、関数本文を
分割する
➢ 分割された処理を、Promiseの
"then"メソッドで順番に実行する
➢ 例外は"catch"メソッドで補足する
§1 JavaScriptの非同期処理(再掲)
プログラムを、1行ずつ完了するまで待ちながら進める"同期処理"に対して...
待ち時間が発生するような処理(ファイルの読み書き、HTTP通信など)の完了を待たず、
続く行のプログラムを実行した後で結果を処理するテクニック。
➢ 未完了の行が発生しても、プログラムの実行を進める仕組み
➢ 未完了だった行の処理が完了した後に結果を処理する仕組み
が必要。
JavaScriptはシングルプロセス・シングルスレッドで動作するプログラミング言語。
⚠︎ 注意 : 非同期処理を実現するための仕組みは、必ずしも他のプログラミング言語と
同じでない!!
JavaScriptランタイムの動作原理を学び、非同期処理を支える言語機能を活用することで
理解を深めていく。
目次(再掲)
§1 JavaScriptの非同期処理
§1.1 コールバックについて
➢ イベントループ
➢ setTimeout()の例
§1.2 委譲(delegate)について
➢ イベントハンドラの登録
➢ Promiseの使用例
➢ Promiseの実装例
§1.3 async/awaitについて
➢ 糖衣構文(シンタックスシュガー)
参考文献
参考文献
➢ Asynchronous JavaScript
➢ mdn web docs - Asynchronous JavaScript
➢ mdn web docs - Callback function
➢ mdn web docs - The event loop
➢ Promise
➢ さくらのナレッジ - JavaScriptの非同期処理を理解する その1 〜コールバック編〜
➢ さくらのナレッジ - JavaScriptの非同期処理を理解する その2 〜Promise編〜
➢ Innolitics - Decorating Async JavaScript Functions
➢ Deep JavaScript - Environments: under the hood of variables
➢ Aysnc/await
➢ mdn web docs - async function
➢ mdn web docs - Iterators and generators
➢ mdn web docs - Closures

More Related Content

Recently uploaded

デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)UEHARA, Tetsutaro
 
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfAWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfFumieNakayama
 
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?akihisamiyanaga1
 
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NTT DATA Technology & Innovation
 
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfクラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfFumieNakayama
 
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...博三 太田
 
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineerYuki Kikuchi
 
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)Hiroshi Tomioka
 

Recently uploaded (8)

デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
デジタル・フォレンジックの最新動向(2024年4月27日情洛会総会特別講演スライド)
 
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdfAWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
AWS の OpenShift サービス (ROSA) を使った OpenShift Virtualizationの始め方.pdf
 
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
CTO, VPoE, テックリードなどリーダーポジションに登用したくなるのはどんな人材か?
 
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
 
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdfクラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
クラウドネイティブなサーバー仮想化基盤 - OpenShift Virtualization.pdf
 
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察  ~Text-to-MusicとText-To-ImageかつImage-to-Music...
モーダル間の変換後の一致性とジャンル表を用いた解釈可能性の考察 ~Text-to-MusicとText-To-ImageかつImage-to-Music...
 
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
自分史上一番早い2024振り返り〜コロナ後、仕事は通常ペースに戻ったか〜 by IoT fullstack engineer
 
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
 

Featured

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 

Featured (20)

Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 

JavaScriptの非同期処理