You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
]).then(alert);//1,2,3 when promises are ready: each promise contributes an array member
30
+
]).then(alert);//모든 프라미스가 준비되면 1, 2, 3이 반환됩니다. 프라미스 각각은 배열을 구성하는 요소가 됩니다.
31
31
```
32
32
33
-
Please note that the order of resulting array members is the same as source promises. Even though the first promise takes the longest time to resolve, it's still first in the array of results.
33
+
반환되는 배열엔`Promise.all`에 들어가는 프라미스와 동일한 순서로 요소가 저장된다는 점에 유의하시기 바랍니다. 첫 번째 프라미스가 가장 늦게 이행되더라도 그 결과는 배열의 첫 번째 요소가 됩니다.
34
34
35
-
A common trick is to map an array of job data into an array of promises, and then wrap that into`Promise.all`.
35
+
작업해야 할 데이터(아래 예시에선 url)가 담긴 배열을 프라미스 배열로 매핑하고, 이 배열을`Promise.all`로 감싸는 것은 흔히 사용되는 트릭입니다.
36
36
37
-
For instance, if we have an array of URLs, we can fetch them all like this:
A bigger example with fetching user information for an array of GitHub users by their names (we could fetch an array of goods by their ids, the logic is same):
56
+
좀 더 복잡한 예시를 살펴봅시다. GitHub 유저네임이 담긴 배열을 사용해 사용자 정보를 가져오는 예시입니다(동일한 로직을 사용해 id로 장바구니 목록을 불러올 수 있습니다).
57
57
58
58
```js run
59
59
let names= ['iliakan','remy','jeresig'];
@@ -62,22 +62,22 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
62
62
63
63
Promise.all(requests)
64
64
.then(responses=> {
65
-
//all responses are resolved successfully
65
+
//모든 응답이 성공적으로 이행되었습니다.
66
66
for(let responseof responses) {
67
-
alert(`${response.url}:${response.status}`);//shows 200 for every url
**If any of the promises is rejected, the promise returned by`Promise.all` immediately rejects with that error.**
78
+
**프라미스가 하나라도 거부되면`Promise.all`이 반환한 프라미스는 에러와 함께 바로 거부됩니다.**
79
79
80
-
For instance:
80
+
예시:
81
81
82
82
```js run
83
83
Promise.all([
@@ -89,56 +89,56 @@ Promise.all([
89
89
]).catch(alert);// Error: 에러 발생!
90
90
```
91
91
92
-
Here the second promise rejects in two seconds. That leads to immediate rejection of`Promise.all`, so`.catch` executes: the rejection error becomes the outcome of the whole`Promise.all`.
92
+
2초 후 두 번째 프라미스가 거부되면`Promise.all` 전체가 거부되기 때문에`.catch`가 실행됩니다. 거부된 프라미스의 에러는`Promise.all` 전체의 결과가 됩니다.
93
93
94
-
```warn header="In case of an error, other promises are ignored"
95
-
If one promise rejects,`Promise.all` immediately rejects, completely forgetting about the other ones in the list. Their results are ignored.
94
+
```warn header="에러가 발생하면 다른 프라미스는 무시됩니다."
95
+
프라미스가 하나라도 거부되면`Promise.all`은 즉시 거부되고 배열에 저장된 다른 프라미스의 결과는 완전히 사라집니다. 실패하지 않은 프라미스라도 결과가 무시됩니다.
96
96
97
-
For example, if there are multiple`fetch` calls, like in the example above, and one fails, other ones will still continue to execute, but`Promise.all` won't watch them anymore. They will probably settle, but the result will be ignored.
97
+
위 예제처럼`fetch`를 여러 번 호출하고, 그중 하나가 실패해도 다른 호출은 계속 실행됩니다. 그러나`Promise.all`은 다른 호출을 더 이상 신경 쓰지 않습니다. 프라미스가 처리되긴 하겠지만 그 결과는 무시됩니다.
98
98
99
-
`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](info:fetch-abort) we'll cover`AbortController` that can help with that, but it's not a part of the Promise API.
99
+
프라미스에는 '취소'라는 개념이 없어서`Promise.all`도 프라미스를 취소하지 않습니다. [또 다른 챕터](info:fetch-abort)에서 배울`AbortController`를 사용하면 프라미스 취소가 가능하긴 하지만 이는 프라미스 API는 아닙니다.
Normally,`Promise.all(...)` accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's passed to the resulting array "as is".
102
+
````smart header="`이터러블 객체`가 아닌 '일반' 값도`Promise.all(iterable)`에 넘길 수 있습니다."
103
+
`Promise.all(...)`은 대게 프라미스가 요소인 이러터블 객체(대부분 배열)를 받습니다. 그런데 프라미스가 아닌 객체가 배열을 구성하면, 요소가 '그대로' 결과 배열로 전달됩니다.
104
104
105
-
For instance, here the results are`[1, 2, 3]`:
105
+
아래 예시의 결과는`[1, 2, 3]`입니다.
106
106
107
107
```js run
108
108
Promise.all([
109
109
newPromise((resolve,reject)=> {
110
110
setTimeout(()=>resolve(1),1000)
111
111
}),
112
112
2,
113
-
3
113
+
3
114
114
]).then(alert);// 1, 2, 3
115
115
```
116
116
117
-
So we are able to pass ready values to`Promise.all` where convenient.
117
+
따라서 이미 결과를 알고 있는 값을`Promise.all`을 사용해 보낼 수 있습니다.
118
118
````
119
119
120
120
## Promise.allSettled
121
121
122
122
[recent browser="new"]
123
123
124
-
`Promise.all` rejects as a whole if any promise rejects. That's good for "all or nothing" cases, when we need *all* results to go on:
124
+
`Promise.all`은 프라미스가 하나라도 거절되면 전체를 거절합니다. 따라서, 프라미스 결과가 *모두* 필요할 때같이 "모 아니면 도" 같은 상황에 유용합니다.
125
125
126
126
```js
127
127
Promise.all([
128
128
fetch('/template.html'),
129
129
fetch('/style.css'),
130
130
fetch('/data.json')
131
-
]).then(render); // rendermethod needs results of all fetches
131
+
]).then(render); // render메서드는 모든 fetch 메서드의 결괏값이 필요합니다.
132
132
```
133
133
134
-
`Promise.allSettled` waits for all promises to settle. The resulting array has:
134
+
반면,`Promise.allSettled`는 모든 프라미스가 처리될 때까지 기다립니다. 반환되는 배열은 다음과 같은 요소를 갖습니다.
135
135
136
-
- `{status:"fulfilled", value:result}` for successful responses,
137
-
- `{status:"rejected", reason:error}` for errors.
136
+
-응답이 성공할 경우 --`{status:"fulfilled", value:result}`
137
+
-에러가 발생한 경우 --`{status:"rejected", reason:error}`
138
138
139
-
For example, we'd like to fetch the information about multiple users. Even if one request fails, we're still interested in the others.
139
+
`fetch`를 사용해 여러 명의 정보를 가져오고 있다고 가정해봅시다. 요청 하나가 실패해도 다른 요청 결과는 여전히 필요합니다.
@@ -169,11 +169,11 @@ The `results` in the line `(*)` above will be:
169
169
]
170
170
```
171
171
172
-
So, for each promise we get its status and `value/error`.
172
+
`Promise.allSettled`를 사용하면 이처럼 각 프라미스의 상태와 `값 또는 에러`를 받을 수 있습니다.
173
173
174
-
###Polyfill
174
+
###폴리필
175
175
176
-
If the browser doesn't support`Promise.allSettled`, it's easy to polyfill:
176
+
브라우저가`Promise.allSettled`를 지원하지 않는다면 폴리필을 구현하면 됩니다.
177
177
178
178
```js
179
179
if(!Promise.allSettled) {
@@ -189,23 +189,23 @@ if(!Promise.allSettled) {
189
189
}
190
190
```
191
191
192
-
In this code,`promises.map` takes input values, turns into promises (just in case a non-promise was passed) with`p => Promise.resolve(p)`, and then adds`.then`handler to every one.
192
+
위 코드에서`promises.map`은 입력값을 받아`p => Promise.resolve(p)`를 사용해 이를 프라미스로 변경합니다(프라미스가 아닌 값을 받은 경우). 그리고 모든 프라미스에`.then`핸들러를 덧붙입니다.
193
193
194
-
That handler turns a successful result`v` into`{state:'fulfilled', value:v}`, and an error `r` into`{state:'rejected', reason:r}`. That's exactly the format of`Promise.allSettled`.
194
+
`then` 핸들러는 성공한 프라미스의 결괏값`v`를`{state:'fulfilled', value:v}`로, 실패한 프라미스의 결괏값 `r`을`{state:'rejected', reason:r}`로 변경합니다.`Promise.allSettled`의 구성방식과 동일하게 말이죠.
195
195
196
-
Then we can use`Promise.allSettled` to get the results or *all* given promises, even if some of them reject.
196
+
이렇게 폴리필을 구현하면 몇몇 프라미스가 거부되더라도`Promise.allSettled`를 사용해 주어진 프라미스 *전체*의 결과를 얻을 수 있습니다.
197
197
198
198
## Promise.race
199
199
200
-
Similar to`Promise.all`, but waits only for the first settled promise, and gets its result (or error).
200
+
`Promise.race`는`Promise.all`와 비슷합니다. 다만 가장 먼저 처리되는 프라미스의 결과(혹은 에러)를 반환합니다.
201
201
202
-
The syntax is:
202
+
문법은 다음과 같습니다.
203
203
204
204
```js
205
205
let promise = Promise.race(iterable);
206
206
```
207
207
208
-
For instance, here the result will be`1`:
208
+
아래 예시의 결과는`1`입니다.
209
209
210
210
```js run
211
211
Promise.race([
@@ -215,26 +215,26 @@ Promise.race([
215
215
]).then(alert); // 1
216
216
```
217
217
218
-
The first promise here was fastest, so it became the result. After the first settled promise "wins the race", all further results/errors are ignored.
218
+
첫 번째 프라미스가 가장 빨리 처리상태가 되기 때문에 이 프라미스의 처리 결과가 result 값이 됩니다. "경주(race)의 승자"가 나타나면 다른 프라미스의 결과 또는 에러는 무시됩니다.
219
219
220
220
221
221
## Promise.resolve/reject
222
222
223
-
Methods`Promise.resolve` and`Promise.reject` are rarely needed in modern code, because`async/await`syntax (we'll cover it in [a bit later](info:async-await)) makes them somewhat obsolete.
223
+
프라미스 메서드`Promise.resolve`와`Promise.reject`는`async/await`문법([뒤에서](info:async-await) 다룸) 때문에 쓸모없어졌기 때문에 근래에는 거의 사용하지 않습니다.
224
224
225
-
We cover them here for completeness, and for those who can't use`async/await` for some reason.
225
+
여기선 튜토리얼의 완성도를 높이고 어떤 이유 때문이라도`async/await`를 사용하지 못하는 분들을 위해 이 메서드들에 대해서 다루겠습니다.
226
226
227
-
- `Promise.resolve(value)` creates a resolved promise with the result`value`.
let promise = new Promise(resolve => resolve(value));
233
233
```
234
234
235
-
The method is used for compatibility, when a function is expected to return a promise.
235
+
호환성을 유지하면서 프라미스를 반환하는 함수를 구현할 때 `Promise.resolve`를 사용할 수 있습니다.
236
236
237
-
For example, `loadCached` function below fetches URL and remembers (caches) its content. For future calls with the same URL it immediately gets the previous content from cache, but uses`Promise.resolve` to make a promise of it, so that the returned value is always a promise:
237
+
아래 함수 `loadCached`는 인수로 받은 URL에 `fetch`를 호출하고, 그 결과를 기억(cache)합니다. 나중에 동일한 URL을 대상으로 `fetch`를 호출하면 캐시에서 즉시 저장된 내용을 가져옵니다. 그런데 이때`Promise.resolve`를 사용하면 반환 값이 항상 프라미스가 되게 할 수 있습니다.
238
238
239
239
```js
240
240
let cache = new Map();
@@ -255,30 +255,30 @@ function loadCached(url) {
255
255
}
256
256
```
257
257
258
-
We can write`loadCached(url).then(…)`, because the function is guaranteed to return a promise. We can always use`.then` after `loadCached`. That's the purpose of`Promise.resolve` in the line `(*)`.
258
+
함수를 호출하면 항상 프라미스가 반환되기 때문에`loadCached(url).then(…)`을 사용할 수 있습니다. `loadCached` 뒤에 항상`.then`을 쓸 수 있죠. `(*)`로 표시한 줄에서`Promise.resolve`를 사용한 이유가 바로 여기에 있습니다.
259
259
260
260
### Promise.reject
261
261
262
-
- `Promise.reject(error)` creates a rejected promise with`error`.
let promise = new Promise((resolve, reject) => reject(error));
268
268
```
269
269
270
-
In practice, this method is almost never used.
270
+
실무에서 이 메서드를 쓸 일은 거의 없습니다.
271
271
272
-
##Summary
272
+
##요약
273
273
274
-
There are 5 static methods of `Promise` class:
274
+
`Promise` 클래스에는 5가지 정적 메서드가 있습니다.
275
275
276
-
1. `Promise.all(promises)` --waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, then it becomes the error of`Promise.all`, and all other results are ignored.
277
-
2. `Promise.allSettled(promises)` (recently added method) --waits for all promises to settle and returns their results as array of objects with: