Skip to content

Commit 6445ef9

Browse files
author
hyemi-lee-nuvilab
committed
docs: promise.all task & solution 신규 번역
1 parent a23bed7 commit 6445ef9

3 files changed

Lines changed: 44 additions & 44 deletions

File tree

1-js/11-async/08-async-await/02-rewrite-async-2/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
속임수랄게 없는 문제입니다. `demoGithubUser`안의 `.catch``try..catch`로 교체하고 필요한 곳에 `async/await`를 추가하면 됩니다.
2+
속임수랄게 없는 문제입니다. `demoGithubUser`안의 `.catch``try..catch`로 교체하고 필요한 곳에 `async/await`를 추가하면 됩니다.
33

44
```js run
55
class HttpError extends Error {
@@ -46,4 +46,4 @@ async function demoGithubUser() {
4646
}
4747

4848
demoGithubUser();
49-
```
49+
```

1-js/11-async/08-async-await/04-promise-all-failure/solution.md

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,52 @@
11

2-
The root of the problem is that `Promise.all` immediately rejects when one of its promises rejects, but it do nothing to cancel the other promises.
2+
문제의 원인은 `Promise.all`이 프라미스 중 하나라도 거부되면 즉시 거부되지만, 나머지 프라미스를 취소하지는 않는다는 데 있습니다.
33

4-
In our case, the second query fails, so `Promise.all` rejects, and the `try...catch` block catches this error.Meanwhile, other promises are *not affected* - they independently continue their execution. In our case, the third query throws an error of its own after a bit of time. And that error is never caught, we can see it in the console.
4+
위 예시에서는 두 번째 쿼리가 실패하므로 `Promise.all`이 거부되고, `try...catch` 블록이 이 에러를 잡습니다. 한편 다른 프라미스는 *아무 영향도 받지 않습니다*. 각자 독립적으로 계속 실행됩니다. 예시에서는 잠시 후 세 번째 쿼리가 자체적으로 에러를 던집니다. 이 에러는 어디에서도 잡히지 않으므로 콘솔에서 확인할 수 있습니다.
55

6-
The problem is especially dangerous in server-side environments, such as Node.js, when an uncaught error may cause the process to crash.
6+
이 문제는 Node.js 같은 서버 측 환경에서 특히 위험합니다. 잡히지 않은 에러로 인해 프로세스가 중단될 수 있기 때문입니다.
77

8-
How to fix it?
8+
어떻게 고칠 수 있을까요?
99

10-
An ideal solution would be to cancel all unfinished queries when one of them fails. This way we avoid any potential errors.
10+
가장 이상적인 해결책은 쿼리 중 하나가 실패했을 때 아직 끝나지 않은 쿼리를 모두 취소하는 것입니다. 이렇게 하면 잠재적인 에러를 피할 수 있습니다.
1111

12-
However, the bad news is that service calls (such as `database.query`) are often implemented by a 3rd-party library which doesn't support cancellation. Then there's no way to cancel a call.
12+
하지만 안타깝게도 `database.query` 같은 서비스 호출은 취소 기능을 지원하지 않는 서드파티 라이브러리로 구현된 경우가 많습니다. 이런 경우 호출을 취소할 방법이 없습니다.
1313

14-
As an alternative, we can write our own wrapper function around `Promise.all` which adds a custom `then/catch` handler to each promise to track them: results are gathered and, if an error occurs, all subsequent promises are ignored.
14+
대안으로 `Promise.all`을 감싸는 래퍼 함수를 직접 작성할 수 있습니다. 이 함수는 각 프라미스에 커스텀 `then/catch` 핸들러를 붙여 상태를 추적합니다. 결과를 모으다가 에러가 발생하면 그 이후 프라미스는 모두 무시합니다.
1515

1616
```js
1717
function customPromiseAll(promises) {
1818
return new Promise((resolve, reject) => {
1919
const results = [];
2020
let resultsCount = 0;
21-
let hasError = false; // we'll set it to true upon first error
21+
let hasError = false; // 첫 번째 에러가 발생하면 true로 바꿉니다.
2222

2323
promises.forEach((promise, index) => {
2424
promise
2525
.then(result => {
26-
if (hasError) return; // ignore the promise if already errored
26+
if (hasError) return; // 이미 에러가 발생했다면 이 프라미스를 무시합니다.
2727
results[index] = result;
2828
resultsCount++;
2929
if (resultsCount === promises.length) {
30-
resolve(results); // when all results are ready - successs
30+
resolve(results); // 모든 결과가 준비되면 성공입니다.
3131
}
3232
})
3333
.catch(error => {
34-
if (hasError) return; // ignore the promise if already errored
35-
hasError = true; // wops, error!
36-
reject(error); // fail with rejection
34+
if (hasError) return; // 이미 에러가 발생했다면 이 프라미스를 무시합니다.
35+
hasError = true; // 에러가 발생했습니다.
36+
reject(error); // 거부 상태로 실패 처리합니다.
3737
});
3838
});
3939
});
4040
}
4141
```
4242

43-
This approach has an issue of its own - it's often undesirable to `disconnect()` when queries are still in the process.
43+
이 방식에도 문제가 있습니다. 쿼리가 아직 처리 중일 때 `disconnect()`를 호출하는 것은 대개 바람직하지 않습니다.
4444

45-
It may be important that all queries complete, especially if some of them make important updates.
45+
특히 일부 쿼리가 중요한 업데이트를 수행한다면 모든 쿼리가 완료되는 것이 중요할 수 있습니다.
4646

47-
So we should wait until all promises are settled before going further with the execution and eventually disconnecting.
47+
따라서 실행을 계속 진행하고 마지막에 연결을 끊기 전에 모든 프라미스가 처리될 때까지 기다려야 합니다.
4848

49-
Here's another implementation. It behaves similar to `Promise.all` - also resolves with the first error, but waits until all promises are settled.
49+
다른 구현을 살펴봅시다. 이 구현은 `Promise.all`과 비슷하게 동작합니다. 첫 번째 에러와 함께 거부되지만, 모든 프라미스가 처리될 때까지 기다립니다.
5050

5151
```js
5252
function customPromiseAllWait(promises) {
@@ -80,16 +80,16 @@ function customPromiseAllWait(promises) {
8080
}
8181
```
8282

83-
Now `await customPromiseAllWait(...)` will stall the execution until all queries are processed.
83+
이제 `await customPromiseAllWait(...)`는 모든 쿼리가 처리될 때까지 실행을 멈춥니다.
8484

85-
This is a more reliable approach, as it guarantees a predictable execution flow.
85+
실행 흐름을 예측할 수 있게 보장하므로 더 안정적인 방식입니다.
8686

87-
Lastly, if we'd like to process all errors, we can use either use `Promise.allSettled` or write a wrapper around it to gathers all errors in a single [AggregateError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) object and rejects with it.
87+
마지막으로 모든 에러를 처리하고 싶다면 `Promise.allSettled`를 사용하면 됩니다. 또는 `Promise.allSettled`를 감싸는 래퍼를 작성해 모든 에러를 하나의 [AggregateError](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) 객체에 모아 거부할 수도 있습니다.
8888

8989
```js
90-
// wait for all promises to settle
91-
// return results if no errors
92-
// throw AggregateError with all errors if any
90+
// 모든 프라미스가 처리될 때까지 기다립니다.
91+
// 에러가 없으면 결과를 반환합니다.
92+
// 에러가 하나라도 있으면 모든 에러가 담긴 AggregateError를 던집니다.
9393
function allOrAggregateError(promises) {
9494
return Promise.allSettled(promises).then(results => {
9595
const errors = [];
Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11

2-
# Dangerous Promise.all
2+
# 위험한 Promise.all
33

4-
`Promise.all` is a great way to parallelize multiple operations. It's especially useful when we need to make parallel requests to multiple services.
4+
`Promise.all`은 여러 작업을 병렬로 처리할 때 아주 유용합니다. 여러 서비스에 병렬로 요청을 보내야 할 때 특히 빛을 발합니다.
55

6-
However, there's a hidden danger. We'll see an example in this task and explore how to avoid it.
6+
하지만 숨어 있는 위험이 있습니다. 이번 과제에서는 예시를 통해 어떤 위험이 있는지 살펴보고 이를 피하는 방법을 알아봅시다.
77

8-
Let's say we have a connection to a remote service, such as a database.
8+
데이터베이스 같은 원격 서비스에 연결한다고 가정해 봅시다.
99

10-
There're two functions: `connect()` and `disconnect()`.
10+
`connect()``disconnect()`라는 두 함수가 있습니다.
1111

12-
When connected, we can send requests using `database.query(...)` - an async function which usually returns the result but also may throw an error.
12+
연결된 상태에서는 `database.query(...)`를 사용해 요청을 보낼 수 있습니다. `database.query(...)`는 보통 결과를 반환하지만 에러를 던질 수도 있는 비동기 함수입니다.
1313

14-
Here's a simple implementation:
14+
간단히 구현하면 다음과 같습니다.
1515

1616
```js
1717
let database;
@@ -28,21 +28,21 @@ function disconnect() {
2828
database = null;
2929
}
3030

31-
// intended usage:
31+
// 사용법:
3232
// connect()
3333
// ...
34-
// database.query(true) to emulate a successful call
35-
// database.query(false) to emulate a failed call
34+
// database.query(true)는 성공한 호출을 흉내 냅니다.
35+
// database.query(false)는 실패한 호출을 흉내 냅니다.
3636
// ...
3737
// disconnect()
3838
```
3939

40-
Now here's the problem.
40+
이제 문제가 되는 부분을 살펴봅시다.
4141

42-
We wrote the code to connect and send 3 queries in parallel (all of them take different time, e.g. 100, 200 and 300ms), then disconnect:
42+
연결한 뒤 쿼리 세 개를 병렬로 보내고, 이후 연결을 끊는 코드를 작성했습니다. 각 쿼리는 100, 200, 300ms처럼 서로 다른 시간이 걸립니다.
4343

4444
```js
45-
// Helper function to call async function `fn` after `ms` milliseconds
45+
// `ms` 밀리초 뒤에 비동기 함수 `fn`을 호출하는 헬퍼 함수
4646
function delay(fn, ms) {
4747
return new Promise((resolve, reject) => {
4848
setTimeout(() => fn().then(resolve, reject), ms);
@@ -54,16 +54,16 @@ async function run() {
5454

5555
try {
5656
await Promise.all([
57-
// these 3 parallel jobs take different time: 100, 200 and 300 ms
58-
// we use the `delay` helper to achieve this effect
57+
// 병렬 작업 세 개는 각각 100, 200, 300ms로 서로 다른 시간이 걸립니다.
58+
// 이 효과를 내기 위해 `delay` 헬퍼를 사용합니다.
5959
*!*
6060
delay(() => database.query(true), 100),
6161
delay(() => database.query(false), 200),
6262
delay(() => database.query(false), 300)
6363
*/!*
6464
]);
6565
} catch(error) {
66-
console.log('Error handled (or was it?)');
66+
console.log('에러를 처리했습니다. 정말 그럴까요?');
6767
}
6868

6969
disconnect();
@@ -72,8 +72,8 @@ async function run() {
7272
run();
7373
```
7474

75-
Two of these queries happen to be unsuccessful, but we're smart enough to wrap the `Promise.all` call into a `try..catch` block.
75+
세 쿼리 중 두 개는 실패합니다. 그래도 `Promise.all` 호출을 `try..catch` 블록으로 감싸 두었으니 충분해 보입니다.
7676

77-
However, this doesn't help! This script actually leads to an uncaught error in console!
77+
하지만 이 방법으로는 부족합니다! 실제로 이 스크립트는 콘솔에 잡히지 않은 에러를 남깁니다.
7878

79-
Why? How to avoid it?
79+
왜 이런 일이 생길까요? 어떻게 피할 수 있을까요?

0 commit comments

Comments
 (0)