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
Promisification -- is a long word for a simple transform. It's conversion of a function that accepts a callback into a function returning a promise.
3
+
콜백을 받는 함수를 프라미스를 반환하는 함수로 바꾸는 것을 '프라미스화(promisification)'라고 합니다.
4
4
5
-
Such transforms are often needed in real-life, as many functions and libraries are callback-based. But promises are more convenient. So it makes sense to promisify those.
5
+
콜백보다는 프라미스가 더 편리하기 때문에, 구현을 하다 보면 콜백 기반 함수와 라이브러리를 프라미스를 반환하는 함수로 바꾸는 게 좋은 경우가 종종 생길 겁니다.
6
6
7
-
For instance, we have `loadScript(src, callback)`from the chapter <info:callbacks>.
7
+
<info:callbacks> 챕터에서 사용했던 `loadScript(src, callback)`예시를 사용해 프라미스화에 대해 좀 더 자세히 알아봅시다.
8
8
9
9
```js run
10
10
functionloadScript(src, callback) {
11
11
let script =document.createElement('script');
12
12
script.src= src;
13
13
14
14
script.onload= () =>callback(null, script);
15
-
script.onerror= () =>callback(newError(`Script load error for ${src}`));
15
+
script.onerror= () =>callback(newError(`${src}를 불러오는 도중에 에러가 발생함`));
16
16
17
17
document.head.append(script);
18
18
}
@@ -21,7 +21,7 @@ function loadScript(src, callback) {
Let's promisify it. The new`loadScriptPromise(src)` function will do the same, but accept only `src` (no `callback`) and return a promise.
24
+
`loadScript(src, callback)`를 이제 프라미스화해봅시다. 새로운 함수`loadScriptPromise(src)`는 `loadScript`와 동일하게 동작하지만 `callback`을 제외한 `src`만 인수로 받아야 하고, 프라미스를 반환해야 합니다.
25
25
26
26
```js
27
27
letloadScriptPromise=function(src) {
@@ -33,60 +33,60 @@ let loadScriptPromise = function(src) {
33
33
})
34
34
}
35
35
36
-
//usage:
36
+
//사용법:
37
37
// loadScriptPromise('path/script.js').then(...)
38
38
```
39
39
40
-
Now `loadScriptPromise` fits well in promise-based code.
40
+
새롭게 구현한 `loadScriptPromise`는 프라미스 기반 코드와 잘 융화됩니다.
41
41
42
-
As we can see, it delegates all the work to the original `loadScript`, providing its own callback that translates to promise `resolve/reject`.
42
+
예시에서 볼 수 있듯이, `loadScriptPromise`는 기존 함수 `loadScript`에 모든 일을 위임합니다. `loadScript`의 콜백은 스크립트 로딩 상태에 따라 `이행` 혹은 `거부`상태의 프라미스를 반환합니다.
43
43
44
-
In practice we'll probably need to promisify many functions, it makes sense to use a helper.
44
+
그런데 실무에선 함수 하나가 아닌 여러 개의 함수를 프라미스화 해야 할 겁니다. 헬퍼 함수를 만드는 게 좋을 것 같네요.
45
45
46
-
We'll call it `promisify(f)`: it accepts a to-promisify function `f` and returns a wrapper function.
46
+
프라미스화를 적용 할 함수 `f`를 받고 래퍼 함수를 반환하는 함수 `promisify(f)`를 만들어봅시다.
47
47
48
-
That wrapper does the same as in the code above: returns a promise and passes the call to the original `f`, tracking the result in a custom callback:
48
+
`promisify(f)`가 반환하는 래퍼 함수는 위 예시와 동일하게 동작할 겁니다. 프라미스를 반환하고 호출을 기존 함수 `f`에 전달하여 커스텀 콜백 내의 결과를 추적해야 하죠.
49
49
50
50
```js
51
51
functionpromisify(f) {
52
-
returnfunction (...args) { //return a wrapper-function
52
+
returnfunction (...args) { //래퍼 함수를 반환함
53
53
returnnewPromise((resolve, reject) => {
54
-
functioncallback(err, result) { //our custom callback for f
54
+
functioncallback(err, result) { //f에 사용할 커스텀 콜백
55
55
if (err) {
56
56
returnreject(err);
57
57
} else {
58
58
resolve(result);
59
59
}
60
60
}
61
61
62
-
args.push(callback); //append our custom callback to the end of f arguments
62
+
args.push(callback); //위에서 만든 커스텀 콜백을 함수 f의 인수 끝에 추가합니다.
63
63
64
-
f.call(this, ...args); //call the original function
64
+
f.call(this, ...args); //기존 함수를 호출합니다.
65
65
});
66
66
};
67
67
};
68
68
69
-
//usage:
69
+
//사용법:
70
70
let loadScriptPromise =promisify(loadScript);
71
71
loadScriptPromise(...).then(...);
72
72
```
73
73
74
-
Here we assume that the original function expects a callback with two arguments `(err, result)`. That's what we encounter most often. Then our custom callback is in exactly the right format, and `promisify` works great for such a case.
74
+
위 예시는 프라미스화 할 함수가 인수가 두 개(`(err, result)`)인 콜백을 받을 것이라 가정하고 작성되었습니다. 십중팔구 이런 상황일 것이고, 커스텀 콜백은 이 상황에 딱 들어맞습니다. `promisify`가 잘 동작하는 것은 말할 것도 없겠죠.
75
75
76
-
But what if the original `f` expects a callback with more arguments`callback(err, res1, res2, ...)`?
76
+
그런데 함수 `f`가 두 개를 초과하는 인수를 가진 콜백,`callback(err, res1, res2, ...)`을 받는다면 어떤 일이 발생할까요?
77
77
78
-
Here's a more advanced version of`promisify`: if called as `promisify(f, true)`, the promise result will be an array of callback results `[res1, res2, ...]`:
78
+
이런 경우를 대비하여 좀 더 진화한`promisify`를 만들어 봅시다. 새롭게 만든 함수를 `promisify(f, true)`형태로 호출하면, 프라미스 결과는 콜백의 성공 케이스(`results`)를 담은 배열, `[res1, res2, ...]`이 됩니다.
function*!*callback(err, ...results*/!*) { //f에 사용할 커스텀 콜백
86
86
if (err) {
87
87
returnreject(err);
88
88
} else {
89
-
//resolve with all callback results if manyArgs is specified
89
+
//manyArgs가 구체적으로 명시되었다면, 콜백의 성공 케이스와 함께 이행 상태가 됩니다.
90
90
*!*resolve(manyArgs ? results : results[0]);*/!*
91
91
}
92
92
}
@@ -98,19 +98,19 @@ function promisify(f, manyArgs = false) {
98
98
};
99
99
};
100
100
101
-
//usage:
101
+
//사용법:
102
102
f =promisify(f, true);
103
103
f(...).then(arrayOfResults=>..., err=>...)
104
104
```
105
105
106
-
For more exotic callback formats, like those without `err` at all: `callback(result)`, we can promisify such functions without using the helper, manually.
106
+
`callback(result)`같이 `err`이 없는 형태나 지금까지 언급하지 않은 형태의 이색적인 콜백도 있을 수 있는데, 이런 경우엔 헬퍼 함수를 사용하지 않고 직접 프라미스화 하면 됩니다.
107
107
108
-
There are also modules with a bit more flexible promisification functions, e.g. [es6-promisify](https://github.com/digitaldesignlabs/es6-promisify). In Node.js, there's a built-in `util.promisify` function for that.
108
+
본 챕터에서 설명한 헬퍼 함수보다 더 유용한 형태의 프라미스화를 도와주는 함수를 제공하는 모둘도 많습니다. [es6-promisify](https://github.com/digitaldesignlabs/es6-promisify)가 대표적인 예입니다. Node.js에선 내장 함수 `util.promisify`를 사용해 프라미스화를 할 수 있습니다.
109
109
110
110
```smart
111
-
Promisification is a great approach, especially when you use `async/await` (see the next chapter), but not a total replacement for callbacks.
111
+
프라미스화는 곧 배우게 될 `async/await`와 함께 사용하면 더 좋습니다. 다만, 콜백을 완전히 대체하지는 못한다는 사실을 기억해 두시기 바랍니다.
112
112
113
-
Remember, a promise may have only one result, but a callback may technically be called many times.
113
+
프라미스는 하나의 결과만 가질 수 있지만, 콜백은 여러 번 호출할 수 있기 때문입니다.
114
114
115
-
So promisification is only meant for functions that call the callback once. Further calls will be ignored.
115
+
따라서 프라미스화는 콜백을 단 한 번 호출하는 함수에만 적용하시기 바랍니다. 프라미스화한 함수의 콜백을 여러 번 호출해도, 두 번째부터는 무시됩니다.
0 commit comments