回答編集履歴
1
動かせるコードを用意した
answer
CHANGED
|
@@ -22,4 +22,73 @@
|
|
|
22
22
|
|
|
23
23
|
ご自身のコードもマークダウンすらできていない状況=**質問すら正しくできていない**状況で、中途半端なコードを出されてもOKなコードには程遠いです。もっと学習して理解度を上げましょう。
|
|
24
24
|
|
|
25
|
-
https://developer.mozilla.org/ja/docs/Web/API/AbortController
|
|
25
|
+
https://developer.mozilla.org/ja/docs/Web/API/AbortController
|
|
26
|
+
|
|
27
|
+
----
|
|
28
|
+
|
|
29
|
+
一応node.jsで動くサンプルコード(express使用)を書いてみました。
|
|
30
|
+
```JavaScript
|
|
31
|
+
import express from 'express';
|
|
32
|
+
const app = express();
|
|
33
|
+
app.get('/', (req, res) => {
|
|
34
|
+
res.send(`
|
|
35
|
+
<p>---</p>
|
|
36
|
+
<p>---</p>
|
|
37
|
+
<p>---</p>
|
|
38
|
+
<button id="stop">stop</button>
|
|
39
|
+
<button id="reset">reset</button>
|
|
40
|
+
<script>
|
|
41
|
+
document.addEventListener('DOMContentLoaded', async()=>{
|
|
42
|
+
let controller = null;
|
|
43
|
+
const stop_button = document.querySelector('#stop');
|
|
44
|
+
const reset_button = document.querySelector('#reset');
|
|
45
|
+
const elems = document.querySelectorAll('p');
|
|
46
|
+
const call_api = async(e) => {
|
|
47
|
+
if (! controller) {
|
|
48
|
+
controller = new AbortController();
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
e.textContent = 'waiting...';
|
|
52
|
+
const response = await fetch('/api', {signal: controller.signal});
|
|
53
|
+
const json = await response.json();
|
|
54
|
+
e.textContent = json[0];
|
|
55
|
+
}
|
|
56
|
+
catch(ex) {
|
|
57
|
+
if (ex instanceof DOMException) {
|
|
58
|
+
e.textContent = 'stopped';
|
|
59
|
+
console.log(ex);
|
|
60
|
+
} else {
|
|
61
|
+
throw ex;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const abort = () => {
|
|
66
|
+
if (controller) {
|
|
67
|
+
const aborting_controller = controller;
|
|
68
|
+
controller = null;
|
|
69
|
+
aborting_controller.abort();
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const start = () => {
|
|
73
|
+
call_api(elems[0]);
|
|
74
|
+
call_api(elems[2]);
|
|
75
|
+
};
|
|
76
|
+
stop_button.addEventListener('click', ()=>{
|
|
77
|
+
abort();
|
|
78
|
+
});
|
|
79
|
+
reset_button.addEventListener('click', ()=>{
|
|
80
|
+
abort();
|
|
81
|
+
elems.forEach(e=>{e.textContent = '---';});
|
|
82
|
+
start();
|
|
83
|
+
});
|
|
84
|
+
start();
|
|
85
|
+
});
|
|
86
|
+
</script>
|
|
87
|
+
`);
|
|
88
|
+
});
|
|
89
|
+
app.get('/api', async (req, res) => {
|
|
90
|
+
await new Promise(resolve=>{setTimeout(resolve, 20000)});
|
|
91
|
+
res.send(['Hello World!']);
|
|
92
|
+
});
|
|
93
|
+
app.listen(3000, ()=>{});
|
|
94
|
+
```
|