AbortControllerを利用するとfetchによるリクエストを中断させることができます。
今回作成するのは、AbortControllerの発動までに3秒の制限時間を授けた簡単なアプリです。fetchにおいて正常な処理が返されるまでに3秒以上経過するとエラーが表示されるようにしています。
送信ボタンをクリックして3秒後にAbortErrorが表示される。
fetchによりindex.html上のフォームからtest-get.phpに値を渡し、index.htmlの<div id=”result”></div>にtest-get.phpから返ってきた値を表示させようとしていますが、test-get.phpでは故意に5秒の遅延を授けているので「AbortError」が表示されます。
fetchについては関連ページをご覧下さい。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<!DOCTYPE html> <head> <meta charset="utf-8"> </head> <html> <body> <form id="form"> <input id="word1" type="text" name="word1" /> <input id="word2" type="text" name="word2" /> <input id="button" type="button" value="送信" /> </form> <div id="result"></div> <script> document.getElementById('button').addEventListener('click', function (e) { const controller = new AbortController(); const signal = controller.signal; setTimeout(() => controller.abort(), 3 * 1000); let data = new FormData(document.getElementById('form')); fetch('test-post.php', { signal, method: 'POST', body: data, }) .then(function (response) { return response.text(); }) .then(function (data) { document.getElementById('result').textContent = data; }) .catch(function (error) { if (error.name === 'AbortError') { document.getElementById('result').textContent = error; } else { document.getElementById('result').textContent = error; } }) }, false) </script> </body> </html> |
21,22行目
AbortControllerのインスタンスを作成しsignalを作成しています。このsignalは、fetchの第2引数に設定します(29行目)。
24行目
3秒経過するとfetchを中断させるabort()が発動されるようにしています。
test-post.php
1 2 3 4 5 6 7 8 |
<?php $word1 = htmlspecialchars($_POST['word1'], ENT_QUOTES, 'UTF-8'); $word2 = htmlspecialchars($_POST['word2'], ENT_QUOTES, 'UTF-8'); sleep(5); echo "{$word1}と{$word2}を入力しました。"; |
6行目
POSTで値を受け取って返すまでに、5秒遅らせています。
参照ページ