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
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'는 놀라울 정도로 이해하기 쉽고, 사용법도 어렵지 않습니다.
4
4
5
-
##Async functions
5
+
##async 함수
6
6
7
-
Let's start with the`async` keyword. It can be placed before afunction, like this:
7
+
`async` 키워드부터 알아봅시다.`async`는function 앞에 위치합니다.
8
8
9
9
```js
10
10
asyncfunctionf() {
11
11
return1;
12
12
}
13
13
```
14
14
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)가 자동으로 감싸게 됩니다.
16
16
17
-
For instance, this function returns a resolved promise with theresult of`1`, let's test it:
17
+
아래 예시의 함수는`result`가`1`인 이행 상태의 프라미스를 반환합니다. 직접 확인해 봅시다.
18
18
19
19
```js run
20
20
asyncfunctionf() {
@@ -24,7 +24,7 @@ async function f() {
24
24
f().then(alert);// 1
25
25
```
26
26
27
-
...We could explicitly return a promise, that would be the same:
27
+
명시적으로 프라미스를 반환하는 것도 가능한데, 결과는 동일합니다.
28
28
29
29
```js run
30
30
asyncfunctionf() {
@@ -34,45 +34,45 @@ async function f() {
34
34
f().then(alert);// 1
35
35
```
36
36
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`는 아주 멋진 녀석이죠.
38
38
39
-
##Await
39
+
##await
40
40
41
-
The syntax:
41
+
await의 문법은 다음과 같습니다.
42
42
43
43
```js
44
-
//works only inside async functions
44
+
//await는 async 함수 안에서만 동작합니다.
45
45
let value=await promise;
46
46
```
47
47
48
-
The keyword`await`makes JavaScript wait until that promise settles and returns its result.
48
+
자바스크립트는`await`키워드를 만나면 프라미스가 처리(settled)될 때까지 기다립니다. 결과는 그 이후 반환됩니다.
49
49
50
-
Here's an example with a promise that resolves in 1 second:
50
+
1초 후 이행되는 프라미스를 예시로 사용하여`await`가 어떻게 동작하는지 살펴봅시다.
51
51
```js run
52
52
asyncfunctionf() {
53
53
54
54
let promise=newPromise((resolve,reject)=> {
55
-
setTimeout(()=>resolve("done!"),1000)
55
+
setTimeout(()=>resolve("완료!"),1000)
56
56
});
57
57
58
58
*!*
59
-
let result=await promise;//wait till the promise resolves (*)
59
+
let result=await promise;//프라미스가 이행될 때까지 기다림 (*)
60
60
*/!*
61
61
62
-
alert(result);// "done!"
62
+
alert(result);// "완료!"
63
63
}
64
64
65
65
f();
66
66
```
67
67
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초 뒤에 '완료!'가 출력됩니다.
69
69
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 리소스가 낭비되지 않습니다.
71
71
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`보다 가독성도 좋고 쓰기도 쉽습니다.
73
73
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`을 사용하면 문법 에러가 발생합니다.
76
76
77
77
```js run
78
78
functionf() {
@@ -83,32 +83,32 @@ function f() {
83
83
}
84
84
```
85
85
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` 안에서만 동작합니다.
87
87
````
88
88
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`를 사용해 다시 작성해봅시다.
90
90
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`를 사용할 수 있도록 합니다.
93
93
94
94
```js run
95
95
async function showAvatar() {
96
96
97
-
//read ourJSON
97
+
// JSON 읽기
98
98
let response = await fetch('/article/promise-chaining/user.json');
99
99
let user = await response.json();
100
100
101
-
//readgithubuser
101
+
// github사용자 정보 읽기
102
102
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
103
103
let githubUser = await githubResponse.json();
104
104
105
-
//show the avatar
105
+
//아바타 보여주기
106
106
let img = document.createElement('img');
107
107
img.src = githubUser.avatar_url;
108
108
img.className = "promise-avatar-example";
109
109
document.body.append(img);
110
110
111
-
//wait 3 seconds
111
+
//3초 대기
112
112
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
113
113
114
114
img.remove();
@@ -119,20 +119,20 @@ async function showAvatar() {
119
119
showAvatar();
120
120
```
121
121
122
-
Pretty clean and easy to read, right? Much better than before.
122
+
코드가 깔끔해지고 읽기도 쉬워졌습니다. 프라미스를 사용한 것보다 훨씬 낫네요.
123
123
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`을 사용할 수 없다는 사실을 잊곤 합니다. 아래와 같은 코드는 동작하지 않습니다.
126
126
127
127
```js run
128
-
//syntax error in top-level code
128
+
//최상위 레벨 코드에선 문법 에러가 발생함
129
129
let response = await fetch('/article/promise-chaining/user.json');
130
130
let user = await response.json();
131
131
```
132
132
133
-
We can wrap it into an anonymous async function, like this:
133
+
이럴 땐 아래와 같이 익명 async 함수로 감싸면 `await`를 사용할 수 있습니다.
134
134
135
-
```js run
135
+
```js
136
136
(async () => {
137
137
let response = await fetch('/article/promise-chaining/user.json');
138
138
let user = await response.json();
@@ -142,10 +142,10 @@ We can wrap it into an anonymous async function, like this:
142
142
143
143
144
144
````
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`를 충분히 사용할 수 있습니다.
147
147
148
-
Here's a demo`Thenable` class, the`await` below accepts its instances:
148
+
아래 예시에 데모용 클래스`Thenable`이 있는데,`await`는 이 클래스의 인스턴스를 받습니다.
149
149
150
150
```js run
151
151
classThenable {
@@ -154,13 +154,13 @@ class Thenable {
154
154
}
155
155
then(resolve,reject) {
156
156
alert(resolve);
157
-
//resolve withthis.num*2 after 1000ms
157
+
//1000밀리초 후에 이행됨(result는this.num*2)
158
158
setTimeout(()=>resolve(this.num*2),1000);// (*)
159
159
}
160
160
};
161
161
162
162
asyncfunctionf() {
163
-
//waits for 1 second, then result becomes 2
163
+
//1초 후, 변수 result는 2가 됨
164
164
let result=awaitnewThenable(1);
165
165
alert(result);
166
166
}
@@ -171,8 +171,8 @@ f();
171
171
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.
172
172
````
173
173
174
-
````smart header="Async class methods"
175
-
To declare anasync class method, just prepend it with `async`:
174
+
````smart header="async 클래스 메서드"
175
+
메서드 이름 앞에 `async`를 추가하면 async 클래스 메서드를 선언할 수 있습니다.
176
176
177
177
```js run
178
178
class Waiter {
@@ -187,42 +187,42 @@ new Waiter()
187
187
.wait()
188
188
.then(alert); // 1
189
189
```
190
-
The meaning is the same: it ensures that the returned value is a promise and enables `await`.
190
+
`async` 메서드와 `async` 함수는 프라미스를 반환하고 `await`를 사용할 수 있다는 점에서 동일합니다.
191
191
192
192
````
193
-
##Error handling
193
+
##에러 핸들링
194
194
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`문을 작성한 것처럼 에러가 던져집니다.
196
196
197
-
This code:
197
+
예시:
198
198
199
199
```js
200
200
asyncfunctionf() {
201
201
*!*
202
-
awaitPromise.reject(newError("Whoops!"));
202
+
awaitPromise.reject(newError("에러 발생!"));
203
203
*/!*
204
204
}
205
205
```
206
206
207
-
...Is the same as this:
207
+
위 코드는 아래 코드와 동일합니다.
208
208
209
209
```js
210
210
asyncfunctionf() {
211
211
*!*
212
-
thrownewError("Whoops!");
212
+
thrownewError("에러 발생!");
213
213
*/!*
214
214
}
215
215
```
216
216
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`가 에러를 던지기 전에 지연이 생깁니다.
218
218
219
-
We can catch that error using`try..catch`, the same way as a regular`throw`:
219
+
`await`가 던진 에러는`throw`가 던진 에러를 해결할 때와 동일하게`try..catch`로 잡을 수 있습니다.
220
220
221
221
```js run
222
222
asyncfunctionf() {
223
223
224
224
try {
225
-
let response=awaitfetch('http://no-such-url');
225
+
let response=awaitfetch('http://유효하지-않은-url');
226
226
}catch(err) {
227
227
*!*
228
228
alert(err);// TypeError: failed to fetch
@@ -233,28 +233,28 @@ async function f() {
233
233
f();
234
234
```
235
235
236
-
In case of an error, the control jumps to the`catch` block. We can also wrap multiple lines:
236
+
에러가 발생하면 제어 흐름이`catch` 블록으로 넘어갑니다. 여러 줄의 코드를`try..catch`로 감싸는 것도 가능합니다.
237
237
238
238
```js run
239
239
asyncfunctionf() {
240
240
241
241
try {
242
-
let response=awaitfetch('/no-user-here');
242
+
let response=awaitfetch('http://유효하지-않은-url');
243
243
let user=awaitresponse.json();
244
244
}catch(err) {
245
-
//catches errors both in fetch and response.json
245
+
//fetch와 response.json에서 발행한 에러 모두를 여기서 잡습니다.
246
246
alert(err);
247
247
}
248
248
}
249
249
250
250
f();
251
251
```
252
252
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`를 추가하면 거부된 프라미스를 처리할 수 있습니다.
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> 챕터에서 설명한 전역 이벤트 핸들러를 사용해 잡을 수 있습니다.
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.
`async/await`을 사용하면`await`가 대기를 처리해주기 때문에`.then`이 거의 필요하지 않습니다. 여기에 더하여`.catch` 대신 일반`try..catch`를 사용할 수도 있죠. 항상 그러한 것은 아니지만,`promise.then`을 사용하는 것보다`async/await`를 사용하는 것이 대게는 더 편리합니다.
271
271
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`를 추가해 최종 결과나 처리하지 못한 에러를 다루는 것이 관행입니다.
273
273
274
-
Like in the line`(*)` of the example above.
274
+
위 예시의`(*)`이 표시된 줄처럼 말이죠.
275
275
```
276
276
277
277
````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
290
290
291
291
````
292
292
293
-
##Summary
293
+
##요약
294
294
295
-
The`async`keyword before a function has two effects:
295
+
function 앞에`async`키워드를 추가하면 두 가지 효과가 있습니다.
296
296
297
-
1.Makes it always return a promise.
298
-
2.Allows to use`await` in it.
297
+
1.함수는 언제나 프라미스를 반환합니다.
298
+
2.함수 안에서`await`를 사용할 수 있습니다.
299
299
300
-
The`await`keyword before a promise makes JavaScript wait until that promise settles, and then:
300
+
프라미스 앞에`await`키워드가 붙으면, 자바스크립트는 프라미스가 처리될 때까지 기다립니다. 그 후엔 조건에 따라 아래와 같은 동작이 이어집니다.
301
301
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를 반환
304
304
305
-
Together they provide a great framework to write asynchronous code that is easy both to read and write.
305
+
`async/await`를 함께 사용하면 읽고, 쓰기 쉬운 비동기 코드를 작성할 수 있습니다.
306
306
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.