1
1
2
- # Fetch: Abort
2
+ # Fetch: 중단
3
3
4
- As we know, ` fetch ` returns a promise. And JavaScript generally has no concept of "aborting" a promise. So how can we abort a ` fetch ` ?
4
+ 알다시피 ` fetch ` 는 프라미스를 반환합니다. 그리고 자바스크립트에는 일반적으로 프라미스 "중단"이라는 개념이 없습니다. 그렇다면 사이트에서 ` fetch ` 가 더는 필요하지 않음을 나타내는 사용자 액션이 일어날 경우, 진행 중인 ` fetch ` 를 어떻게 중단할 수 있을까요 ?
5
5
6
- There's a special built-in object for such purposes: ` AbortController ` , that can be used to abort not only ` fetch ` , but other asynchronous tasks as well .
6
+ 이러한 경우를 위한 ` AbortContoller ` 라고 하는 특별한 내장 객체가 있습니다. 이 객체는 ` fetch ` 를 비롯한 다른 비동기 작업을 중단하는 데 사용할 수 있습니다 .
7
7
8
- The usage is pretty simple:
8
+ 사용법은 매우 직관적입니다.
9
9
10
- - Step 1: create a controller:
10
+ ## AbortController 객체
11
11
12
- ``` js
13
- let controller = new AbortController ();
14
- ```
12
+ 컨트롤러를 생성합니다.
15
13
16
- A controller is an extremely simple object.
14
+ ``` js
15
+ let controller = new AbortController ();
16
+ ```
17
17
18
- - It has a single method ` abort()` , and a single property ` signal` .
19
- - When ` abort()` is called:
20
- - ` abort` event triggers on ` controller.signal`
21
- - ` controller.signal.aborted` property becomes ` true` .
18
+ 컨트롤러는 매우 단순한 객체입니다.
22
19
23
- All parties interested to learn about ` abort()` call set listeners on ` controller.signal` to track it.
20
+ - 단일 메서드인 ` abort() ` 를 갖습니다.
21
+ - ` abort ` 에 대한 이벤트 리스너를 설정할 수 있는 단일 속성 ` signal ` 을 갖습니다.
24
22
25
- Like this (without ` fetch` yet):
23
+ ` abort() ` 가 호출되면
24
+ - ` controller.signal ` 은 ` "abort" ` 이벤트를 내보냅니다.
25
+ - ` controller.signal.aborted ` 속성은 ` true ` 가 됩니다.
26
26
27
- ` ` ` js run
28
- let controller = new AbortController();
29
- let signal = controller.signal;
27
+ 일반적으로 이 프로세스는 두 부분으로 나뉩니다.
28
+ 1 . ` controller.signal ` 에 설정한 리스너에서 취소 가능한 연산을 수행하는 부분
29
+ 2 . 필요할 때 ` controller.abort() ` 를 호출하여 취소하는 부분
30
30
31
- // triggers when controller.abort() is called
32
- signal.addEventListener('abort', () => alert("abort!"));
31
+ 다음은 전체 예시입니다. (아직 ` fetch ` 는 사용하지 않음)
33
32
34
- controller.abort(); // abort!
33
+ ``` js run
34
+ let controller = new AbortController ();
35
+ let signal = controller .signal ;
36
+
37
+ // "signal" 객체를 받아서
38
+ // controller.abort()가 호출되었을 때 실행할 리스너를 설정하는
39
+ // 취소 가능한 연산을 수행하는 부분
40
+ signal .addEventListener (' abort' , () => alert (" abort!" ));
35
41
36
- alert(signal.aborted); // true
37
- ` ` `
42
+ // 취소하는 부분 (나중에 어떤 시점에라도)
43
+ controller . abort (); // abort!
38
44
39
- - Step 2 : pass the ` signal` property to ` fetch` option:
45
+ // 이벤트가 트리거되고 signal.aborted는 true가 됩니다.
46
+ alert (signal .aborted ); // true
47
+ ```
40
48
41
- ` ` ` js
42
- let controller = new AbortController();
43
- fetch(url, {
44
- signal: controller.signal
45
- });
46
- ` ` `
49
+ 보다시피 ` AbortController ` 는 ` abort() ` 가 호출될 때 ` abort ` 이벤트를 전달하는 수단일 뿐입니다.
47
50
48
- The ` fetch ` method knows how to work with ` AbortController ` , it listens to ` abort ` on ` signal ` .
51
+ ` AbortController ` 객체를 사용하지 않더라도 동일한 형태로 이벤트 수신을 구현할 수 있습니다 .
49
52
50
- - Step 3 : to abort, call ` controller.abort() ` :
53
+ 그러나 ` AbortController ` 가 가치있는 이유는 ` fetch ` 가 ` AbortController ` 객체와 함께 작동하는 방법을 알고 있고, 통합되어 있기 때문입니다.
51
54
52
- ` ` ` js
53
- controller.abort();
54
- ` ` `
55
+ ## fetch와 함께 사용하기
55
56
56
- We ' re done: `fetch` gets the event from `signal` and aborts the request .
57
+ ` fetch ` 를 취소하려면 ` AbortController ` 의 ` signal ` 속성을 ` fetch ` 옵션으로 전달합니다 .
57
58
58
- When a fetch is aborted, its promise rejects with an error `AbortError`, so we should handle it, e.g. in `try..catch`:
59
+ ``` js
60
+ let controller = new AbortController ();
61
+ fetch (url, {
62
+ signal: controller .signal
63
+ });
64
+ ```
65
+
66
+ ` fetch ` 메서드는 ` AbortController ` 와 함께 작동하는 방법을 알고 있습니다. ` fetch ` 는 ` signal ` 에 대한 ` abort ` 이벤트를 수신합니다.
67
+
68
+ 중단하려면 ` controller.abort() ` 를 호출합니다.
69
+
70
+ ``` js
71
+ controller .abort ();
72
+ ```
73
+
74
+ 끝났습니다. ` fetch ` 는 ` signal ` 로부터 이벤트를 받고 요청을 중단합니다.
75
+
76
+ ` fetch ` 가 중단되면 프라미스는 ` AbortError ` 와 함께 reject되므로, ` try..catch ` 같은 방식으로 에러를 적절히 처리해야합니다.
77
+
78
+ 다음은 1초 후에 ` fetch ` 를 중단하는 전체 예시입니다.
59
79
60
80
``` js run async
61
81
// abort in 1 second
@@ -67,42 +87,45 @@ try {
67
87
signal: controller .signal
68
88
});
69
89
} catch (err) {
70
- if (err.name == ' AbortError' ) { // handle abort()
90
+ if (err .name == ' AbortError' ) { // abort() 처리
71
91
alert (" Aborted!" );
72
92
} else {
73
93
throw err;
74
94
}
75
95
}
76
96
```
77
97
78
- **`AbortController` is scalable, it allows to cancel multiple fetches at once.**
98
+ ## AbortController는 확장 가능합니다
79
99
80
- For instance, here we fetch many `urls` in parallel, and the controller aborts them all:
100
+ ` AbortController ` 는 확장 가능하며 한 번에 fetch 여러 개를 동시에 취소할 수 있습니다.
101
+
102
+ 다음은 많은 ` urls ` 을 병렬로 fetch하고 단일 컨트롤러를 사용하여 모두 중단하는 코드입니다.
81
103
82
104
``` js
83
- let urls = [...]; // a list of urls to fetch in parallel
105
+ let urls = [... ]; // 병렬로 fetch할 url 목록
84
106
85
107
let controller = new AbortController ();
86
108
109
+ // fetch 프라미스 배열
87
110
let fetchJobs = urls .map (url => fetch (url, {
88
111
signal: controller .signal
89
112
}));
90
113
91
114
let results = await Promise .all (fetchJobs);
92
115
93
- // if controller.abort() is called from elsewhere,
94
- // it aborts all fetches
116
+ // 어딘가 다른 곳에서 controller.abort()가 호출되면
117
+ // 모든 fetch를 중단합니다
95
118
```
96
119
97
- If we have our own asynchronous jobs, different from `fetch`, we can use a single `AbortController` to stop those, together with fetches .
120
+ 만약 ` fetch ` 가 아닌 자체 비동기 태스크가 있을 경우에도 단일 ` AbortController ` 를 사용하여 fetch와 함께 중지할 수 있습니다 .
98
121
99
- We just need to listen to its `abort` event:
122
+ 그저 작업 내에서 ` abort ` 이벤트를 수신하도록 하면 됩니다.
100
123
101
124
``` js
102
125
let urls = [... ];
103
126
let controller = new AbortController ();
104
127
105
- let ourJob = new Promise((resolve, reject) => { // our task
128
+ let ourJob = new Promise ((resolve , reject ) => { // 자체 태스크
106
129
...
107
130
controller .signal .addEventListener (' abort' , reject);
108
131
});
@@ -111,11 +134,15 @@ let fetchJobs = urls.map(url => fetch(url, { // fetches
111
134
signal: controller .signal
112
135
}));
113
136
114
- // Wait for fetches and our task in parallel
137
+ // fetch와 자체 태스크를 병렬로 기다립니다
115
138
let results = await Promise .all ([... fetchJobs, ourJob]);
116
139
117
- // if controller.abort() is called from elsewhere,
118
- // it aborts all fetches and ourJob
140
+ // 어딘가 다른 곳에서 controller.abort()가 호출되면
141
+ // 모든 fetch와 자체 태스크를 중단합니다
119
142
```
120
143
121
- So `AbortController` is not only for `fetch`, it' s a universal object to abort asynchronous tasks, and ` fetch` has built- in integration with it.
144
+ ## 요약
145
+
146
+ - ` AbortController ` 는 ` abort () ` 메서드가 호출될 때 자신의 ` signal ` 속성에 ` abort ` 이벤트를 발생시키는 단순한 객체입니다(또한 ` signal.aborted ` 를 ` true ` 로 설정).
147
+ - ` fetch ` 와 통합: ` signal ` 속성을 옵션으로 전달하면 ` fetch ` 가 ` abort ` 이벤트를 수신하므로 ` fetch ` 를 중단할 수 있습니다.
148
+ - 코드에서 ` AbortController ` 를 사용할 수 있습니다. "` abort() ` 호출" -> "` abort ` 이벤트 수신" 인터랙션은 단순하고 보편적입니다. 심지어 ` fetch ` 없이도 사용할 수 있습니다.
0 commit comments