Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit66d65d3

Browse files
javascript-tutorial#345 [async와 await] 번역
- co-author:@sojeongw- promise.all관련 부분 추가 보완 필요함-javascript-tutorial/en.javascript.info#1548 이슈 반영해야 함
1 parentbdc881d commit66d65d3

File tree

1 file changed

+71
-71
lines changed

1 file changed

+71
-71
lines changed
Lines changed: 71 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
#Async/await
1+
#async와await
22

3-
There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly easy to understand and use.
3+
'async'와 'await'라는 특별한 문법을 사용하면 프라미스를 좀 더 편하게 사용할 수 있습니다. 'async/await'는 놀라울 정도로 이해하기 쉽고, 사용법도 어렵지 않습니다.
44

5-
##Async functions
5+
##async 함수
66

7-
Let's start with the`async` keyword. It can be placed before afunction, like this:
7+
`async` 키워드부터 알아봅시다.`async`function 앞에 위치합니다.
88

99
```js
1010
asyncfunctionf() {
1111
return1;
1212
}
1313
```
1414

15-
The word "async" before afunctionmeans one simple thing: a function always returns a promise. Other values are wrapped in aresolved promise automatically.
15+
function앞의 단어, 'async'는 해당 함수가 항상 프라미스를 반환한다는 것을 의미합니다. 프라미스가 아닌 값은 이행 상태의 프라미스(resolved promise)가 자동으로 감싸게 됩니다.
1616

17-
For instance, this function returns a resolved promise with theresult of`1`, let's test it:
17+
아래 예시의 함수는`result``1`인 이행 상태의 프라미스를 반환합니다. 직접 확인해 봅시다.
1818

1919
```js run
2020
asyncfunctionf() {
@@ -24,7 +24,7 @@ async function f() {
2424
f().then(alert);// 1
2525
```
2626

27-
...We could explicitly return a promise, that would be the same:
27+
명시적으로 프라미스를 반환하는 것도 가능한데, 결과는 동일합니다.
2828

2929
```js run
3030
asyncfunctionf() {
@@ -34,45 +34,45 @@ async function f() {
3434
f().then(alert);// 1
3535
```
3636

37-
So,`async` ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There's another keyword,`await`, that works only inside`async` functions, and it's pretty cool.
37+
`async`가 붙은 함수는 반드시 프라미스를 반환하고, 프라미스가 아닌 것은 프라미스로 감싸 반환합니다. 굉장히 간단하죠? 그런데`async`가 제공하는 기능은 이뿐만이 아닙니다. 또 다른 키워드`await``async` 함수 안에서만 동작합니다.`await`는 아주 멋진 녀석이죠.
3838

39-
##Await
39+
##await
4040

41-
The syntax:
41+
await의 문법은 다음과 같습니다.
4242

4343
```js
44-
//works only inside async functions
44+
//await는 async 함수 안에서만 동작합니다.
4545
let value=await promise;
4646
```
4747

48-
The keyword`await`makes JavaScript wait until that promise settles and returns its result.
48+
자바스크립트는`await`키워드를 만나면 프라미스가 처리(settled)될 때까지 기다립니다. 결과는 그 이후 반환됩니다.
4949

50-
Here's an example with a promise that resolves in 1 second:
50+
1초 후 이행되는 프라미스를 예시로 사용하여`await`가 어떻게 동작하는지 살펴봅시다.
5151
```js run
5252
asyncfunctionf() {
5353

5454
let promise=newPromise((resolve,reject)=> {
55-
setTimeout(()=>resolve("done!"),1000)
55+
setTimeout(()=>resolve("완료!"),1000)
5656
});
5757

5858
*!*
59-
let result=await promise;//wait till the promise resolves (*)
59+
let result=await promise;//프라미스가 이행될 때까지 기다림 (*)
6060
*/!*
6161

62-
alert(result);// "done!"
62+
alert(result);// "완료!"
6363
}
6464

6565
f();
6666
```
6767

68-
The function execution "pauses" at the line`(*)` and resumes when the promise settles, with`result`becoming its result. So the code above shows "done!" in one second.
68+
함수 실행은`(*)`로 표시한 줄에서 잠시 '중단'되었다가 프라미스가 처리되면 다시 시작됩니다. 이때 프라미스 객체의`result`값이 변수 result에 할당됩니다. 따라서 위 예시를 실행하면 1초 뒤에 '완료!'가 출력됩니다.
6969

70-
Let's emphasize:`await` literally makes JavaScript wait until the promise settles, and then go on with the result. That doesn't cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.
70+
`await`('기다리다'라는 뜻을 가진 영단어 - 옮긴이)는 말 그대로 자바스크립트를 프라미스가 처리될 때까지 기다리게 만들고, 프라미스가 처리되면 그 결과와 함께 실행을 재개합니다. 대기 중에 엔진은 다른 일(다른 스크립트를 실행, 이벤트 처리 등)을 할 수 있기 때문에, CPU 리소스가 낭비되지 않습니다.
7171

72-
It's just a more elegant syntax of getting the promise result than`promise.then`, easier to read and write.
72+
`await``promise.then`보다 좀 더 세련되게 프라미스 결과를 얻을 수 있도록 해주는 문법입니다.`promise.then`보다 가독성도 좋고 쓰기도 쉽습니다.
7373

74-
````warn header="Can't use`await` in regular functions"
75-
If we try to use`await` in non-async function, there would be a syntax error:
74+
````warn header="일반 함수에는`await`을 사용할 수 없습니다."
75+
`async` 함수가 아닌데`await`을 사용하면 문법 에러가 발생합니다.
7676

7777
```js run
7878
functionf() {
@@ -83,32 +83,32 @@ function f() {
8383
}
8484
```
8585

86-
We will get this error if we do not put`async` before a function. As said,`await` only works inside an`async function`.
86+
function 앞에`async`를 붙이지 않으면 이런 에러가 발생합니다. 앞서 설명해 드린 바와 같이`await``async function` 안에서만 동작합니다.
8787
````
8888
89-
Let's take the `showAvatar()` example from the chapter<info:promise-chaining>and rewrite it using`async/await`:
89+
<info:promise-chaining>챕터의 `showAvatar()` 예시를`async/await`를 사용해 다시 작성해봅시다.
9090
91-
1.We'll need to replace`.then`calls with`await`.
92-
2.Also we should make the function `async` for them to work.
91+
1.먼저`.then`호출을`await`로 바꿔야 합니다.
92+
2.function 앞에 `async`를 붙여 `await`를 사용할 수 있도록 합니다.
9393
9494
```js run
9595
async function showAvatar() {
9696
97-
//read ourJSON
97+
// JSON 읽기
9898
let response = await fetch('/article/promise-chaining/user.json');
9999
let user = await response.json();
100100
101-
//readgithubuser
101+
// github사용자 정보 읽기
102102
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
103103
let githubUser = await githubResponse.json();
104104
105-
//show the avatar
105+
//아바타 보여주기
106106
let img = document.createElement('img');
107107
img.src = githubUser.avatar_url;
108108
img.className = "promise-avatar-example";
109109
document.body.append(img);
110110
111-
//wait 3 seconds
111+
//3초 대기
112112
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
113113
114114
img.remove();
@@ -119,20 +119,20 @@ async function showAvatar() {
119119
showAvatar();
120120
```
121121
122-
Pretty clean and easy to read, right? Much better than before.
122+
코드가 깔끔해지고 읽기도 쉬워졌습니다. 프라미스를 사용한 것보다 훨씬 낫네요.
123123
124-
````smart header="`await` won't work in the top-level code"
125-
People who are just starting to use`await` tend to forget the fact that we can't use `await` in top-level code. For example, this will not work:
124+
````smart header="`await`는 최상위 레벨 코드에서 작동하지 않습니다."
125+
`await`을 이제 막 사용하기 시작한 분들은 최상위 레벨 코드(top-level code)에 `await`을 사용할 수 없다는 사실을 잊곤 합니다. 아래와 같은 코드는 동작하지 않습니다.
126126
127127
```js run
128-
//syntax error in top-level code
128+
//최상위 레벨 코드에선 문법 에러가 발생함
129129
let response = await fetch('/article/promise-chaining/user.json');
130130
let user = await response.json();
131131
```
132132
133-
We can wrap it into an anonymous async function, like this:
133+
이럴 땐 아래와 같이 익명 async 함수로 감싸면 `await`를 사용할 수 있습니다.
134134
135-
```js run
135+
```js
136136
(async () => {
137137
let response = await fetch('/article/promise-chaining/user.json');
138138
let user = await response.json();
@@ -142,10 +142,10 @@ We can wrap it into an anonymous async function, like this:
142142
143143
144144
````
145-
````smart header="`await` accepts\"thenables\""
146-
Like`promise.then`,`await` allows to use thenable objects (those with a callable`then` method). The idea is that a 3rd-party object may not be a promise, but promise-compatible: if it supports`.then`, that's enough to use with`await`.
145+
````smart header="`await`\'thenables\'를 받습니다."
146+
`promise.then`처럼`await`도 thenable 객체(`then` 메서드가 있는 호출 가능한 객체)를 사용할 수 있게 해줍니다. 서드파티 객체는 프라미스가 아니지만 프라미스와 호환 가능한 객체일 수 있다는 점에서 이런 기능이 생겼습니다. 서드파티 객체가`.then`을 지원하면`await`를 충분히 사용할 수 있습니다.
147147

148-
Here's a demo`Thenable` class, the`await` below accepts its instances:
148+
아래 예시에 데모용 클래스`Thenable`이 있는데,`await`는 이 클래스의 인스턴스를 받습니다.
149149

150150
```js run
151151
classThenable {
@@ -154,13 +154,13 @@ class Thenable {
154154
}
155155
then(resolve,reject) {
156156
alert(resolve);
157-
//resolve withthis.num*2 after 1000ms
157+
//1000밀리초 후에 이행됨(result는this.num*2)
158158
setTimeout(()=>resolve(this.num*2),1000);// (*)
159159
}
160160
};
161161

162162
asyncfunctionf() {
163-
//waits for 1 second, then result becomes 2
163+
//1초 후, 변수 result는 2가 됨
164164
let result=awaitnewThenable(1);
165165
alert(result);
166166
}
@@ -171,8 +171,8 @@ f();
171171
If`await` gets a non-promise object with`.then`, it calls that method providing native functions`resolve`,`reject` as arguments. Then`await` waits until one of them is called (in the example above it happens in the line`(*)`) and then proceeds with the result.
172172
````
173173
174-
````smart header="Async class methods"
175-
To declare anasync class method, just prepend it with `async`:
174+
````smart header="async 클래스 메서드"
175+
메서드 이름 앞에 `async`를 추가하면 async 클래스 메서드를 선언할 수 있습니다.
176176
177177
```js run
178178
class Waiter {
@@ -187,42 +187,42 @@ new Waiter()
187187
.wait()
188188
.then(alert); // 1
189189
```
190-
The meaning is the same: it ensures that the returned value is a promise and enables `await`.
190+
`async` 메서드와 `async` 함수는 프라미스를 반환하고 `await`를 사용할 수 있다는 점에서 동일합니다.
191191
192192
````
193-
##Error handling
193+
##에러 핸들링
194194

195-
If a promise resolves normally, then`await promise` returns the result. But in case of a rejection, it throws the error, just as if there were a`throw` statement at that line.
195+
프라미스가 정상적으로 이행되면`await promise`는 결과를 반환합니다. 그러나 프라미스가 거부되면 마치`throw`문을 작성한 것처럼 에러가 던져집니다.
196196

197-
This code:
197+
예시:
198198

199199
```js
200200
asyncfunctionf() {
201201
*!*
202-
awaitPromise.reject(newError("Whoops!"));
202+
awaitPromise.reject(newError("에러 발생!"));
203203
*/!*
204204
}
205205
```
206206

207-
...Is the same as this:
207+
위 코드는 아래 코드와 동일합니다.
208208

209209
```js
210210
asyncfunctionf() {
211211
*!*
212-
thrownewError("Whoops!");
212+
thrownewError("에러 발생!");
213213
*/!*
214214
}
215215
```
216216

217-
In real situations, the promise may take some time before it rejects. In that case there will be a delay before`await` throws an error.
217+
실제 상황에선 일정 시간이 지난 후에 프라미스가 거부되곤 합니다. 이럴 땐`await`가 에러를 던지기 전에 지연이 생깁니다.
218218

219-
We can catch that error using`try..catch`, the same way as a regular`throw`:
219+
`await`가 던진 에러는`throw`가 던진 에러를 해결할 때와 동일하게`try..catch`로 잡을 수 있습니다.
220220

221221
```js run
222222
asyncfunctionf() {
223223

224224
try {
225-
let response=awaitfetch('http://no-such-url');
225+
let response=awaitfetch('http://유효하지-않은-url');
226226
}catch(err) {
227227
*!*
228228
alert(err);// TypeError: failed to fetch
@@ -233,28 +233,28 @@ async function f() {
233233
f();
234234
```
235235

236-
In case of an error, the control jumps to the`catch` block. We can also wrap multiple lines:
236+
에러가 발생하면 제어 흐름이`catch` 블록으로 넘어갑니다. 여러 줄의 코드를`try..catch`로 감싸는 것도 가능합니다.
237237

238238
```js run
239239
asyncfunctionf() {
240240

241241
try {
242-
let response=awaitfetch('/no-user-here');
242+
let response=awaitfetch('http://유효하지-않은-url');
243243
let user=awaitresponse.json();
244244
}catch(err) {
245-
//catches errors both in fetch and response.json
245+
//fetch와 response.json에서 발행한 에러 모두를 여기서 잡습니다.
246246
alert(err);
247247
}
248248
}
249249

250250
f();
251251
```
252252

253-
If we don't have`try..catch`, then the promise generated by the call of theasyncfunction`f()` becomes rejected. We can append`.catch` to handle it:
253+
`try..catch`가 없으면async함수`f()`를 호출해 만든 프라미스가 거부됩니다.`.catch`를 추가하면 거부된 프라미스를 처리할 수 있습니다.
254254

255255
```js run
256256
asyncfunctionf() {
257-
let response=awaitfetch('http://no-such-url');
257+
let response=awaitfetch('http://유효하지-않은-url');
258258
}
259259

260260
// f() becomes a rejected promise
@@ -263,15 +263,15 @@ f().catch(alert); // TypeError: failed to fetch // (*)
263263
*/!*
264264
```
265265

266-
If we forget to add`.catch` there, then we get an unhandled promise error (viewable in the console).We can catch such errors using a global event handler as described in the chapter<info:promise-error-handling>.
266+
`.catch`를 추가하는 걸 잊으면, 처리되지 않은 프라미스 에러가 발생합니다(콘솔에서 확인).이런 에러는<info:promise-error-handling> 챕터에서 설명한 전역 이벤트 핸들러를 사용해 잡을 수 있습니다.
267267

268268

269-
```smart header="`async/await` and`promise.then/catch`"
270-
When we use`async/await`, we rarely need`.then`, because`await` handles the waiting for us. And we can use a regular`try..catch` instead of`.catch`. That's usually (not always) more convenient.
269+
```smart header="`async/await``promise.then/catch`"
270+
`async/await`을 사용하면`await`가 대기를 처리해주기 때문에`.then`이 거의 필요하지 않습니다. 여기에 더하여`.catch` 대신 일반`try..catch`를 사용할 수도 있죠. 항상 그러한 것은 아니지만,`promise.then`을 사용하는 것보다`async/await`를 사용하는 것이 대게는 더 편리합니다.
271271

272-
But at the top level of the code, when we're outside of any`async` function, we're syntactically unable to use`await`, so it's a normal practice to add`.then/catch` to handle the final result or falling-through errors.
272+
그런데 문법 제약 때문에 최상위 레벨 코드에선`await`를 사용할 수 없으므로,`.then/catch`를 추가해 최종 결과나 처리하지 못한 에러를 다루는 것이 관행입니다.
273273

274-
Like in the line`(*)` of the example above.
274+
위 예시의`(*)`이 표시된 줄처럼 말이죠.
275275
```
276276
277277
````smart header="`async/await` works well with `Promise.all`"
@@ -290,18 +290,18 @@ In case of an error, it propagates as usual: from the failed promise to `Promise
290290

291291
````
292292
293-
##Summary
293+
##요약
294294
295-
The`async`keyword before a function has two effects:
295+
function 앞에`async`키워드를 추가하면 두 가지 효과가 있습니다.
296296
297-
1.Makes it always return a promise.
298-
2.Allows to use`await` in it.
297+
1.함수는 언제나 프라미스를 반환합니다.
298+
2.함수 안에서`await`를 사용할 수 있습니다.
299299
300-
The`await`keyword before a promise makes JavaScript wait until that promise settles, and then:
300+
프라미스 앞에`await`키워드가 붙으면, 자바스크립트는 프라미스가 처리될 때까지 기다립니다. 그 후엔 조건에 따라 아래와 같은 동작이 이어집니다.
301301
302-
1.If it's an error, the exception is generated, same as if`throw error` were called at that very place.
303-
2.Otherwise, it returns the result.
302+
1.에러 발생 -- 에러가 발생한 부분에서 예외가 생성됨(`throw error`를 호출한 것과 동일)
303+
2.에러 미발생 -- 프라미스 객체의 result를 반환
304304
305-
Together they provide a great framework to write asynchronous code that is easy both to read and write.
305+
`async/await`를 함께 사용하면 읽고, 쓰기 쉬운 비동기 코드를 작성할 수 있습니다.
306306
307-
With`async/await` we rarely need to write`promise.then/catch`, but we still shouldn't forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also `Promise.all` is a nice thing to wait for many tasks simultaneously.
307+
`async/await`를 사용하면`promise.then/catch`가 거의 필요 없습니다. 하지만 가끔 `promise.then/catch`를 써야만 하는 경우가 생기기 때문에(예: 가장 바깥 스코프에서 비동기 처리가 필요할 때) `async/await`가 프라미스를 기반으로 한다는 사실을 알고 계셔야 합니다. Also `Promise.all` is a nice thing to wait for many tasks simultaneously.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp