Skip to content

Commit 1b8842d

Browse files
committed
docs: 06-promisify 충돌 해결
1 parent 71ab899 commit 1b8842d

1 file changed

Lines changed: 1 addition & 60 deletions

File tree

1-js/11-async/06-promisify/article.md

Lines changed: 1 addition & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,7 @@
44

55
기능을 구현 하다 보면 콜백보다는 프라미스가 더 편리하기 때문에 콜백 기반 함수와 라이브러리를 프라미스를 반환하는 함수로 바꾸는 게 좋은 경우가 종종 생길 겁니다.
66

7-
<<<<<<< HEAD
87
<info:callbacks> 챕터에서 사용했던 `loadScript(src, callback)` 예시를 사용해 프라미스화에 대해 좀 더 자세히 알아봅시다.
9-
=======
10-
For better understanding, let's see an example.
11-
12-
For instance, we have `loadScript(src, callback)` from the chapter <info:callbacks>.
13-
>>>>>>> upstream/master
148

159
```js run
1610
function loadScript(src, callback) {
@@ -27,19 +21,7 @@ function loadScript(src, callback) {
2721
// loadScript('path/script.js', (err, script) => {...})
2822
```
2923

30-
<<<<<<< HEAD
3124
`loadScript(src, callback)`를 이제 프라미스화해봅시다. 새로운 함수 `loadScriptPromise(src)``loadScript`와 동일하게 동작하지만 `callback`을 제외한 `src`만 인수로 받아야 하고, 프라미스를 반환해야 합니다.
32-
=======
33-
The function loads a script with the given `src`, and then calls `callback(err)` in case of an error, or `callback(null, script)` in case of successful loading. That's a widespread agreement for using callbacks, we saw it before.
34-
>>>>>>> upstream/master
35-
36-
Let's promisify it.
37-
38-
We'll make a new function `loadScriptPromise(src)`, that does the same (loads the script), but returns a promise instead of using callbacks.
39-
40-
In other words, we pass it only `src` (no `callback`) and get a promise in return, that resolves with `script` when the load is successful, and rejects with the error otherwise.
41-
42-
Here it is:
4325
```js
4426
let loadScriptPromise = function(src) {
4527
return new Promise((resolve, reject) => {
@@ -54,10 +36,9 @@ let loadScriptPromise = function(src) {
5436
// loadScriptPromise('path/script.js').then(...)
5537
```
5638

57-
<<<<<<< HEAD
5839
새롭게 구현한 `loadScriptPromise`는 프라미스 기반 코드와 잘 융화됩니다.
5940

60-
예시에서 볼 수 있듯이, `loadScriptPromise`는 기존 함수 `loadScript`에 모든 일을 위임합니다. `loadScript`의 콜백은 스크립트 로딩 상태에 따라 `이행` 혹은 `거부`상태의 프라미스를 반환합니다.
41+
예시에서 볼 수 있듯이, `loadScriptPromise`는 기존 함수 `loadScript`에 모든 일을 위임합니다. `loadScript`의 콜백은 스크립트 로딩 상태에 따라 `이행` 혹은 `거부`상태의 프라미스를 반환합니다.
6142

6243
그런데 실무에선 함수 하나가 아닌 여러 개의 함수를 프라미스화 해야 할 겁니다. 헬퍼 함수를 만드는 게 좋을 것 같네요. 프라미스화를 적용 할 함수 `f`를 받고 래퍼 함수를 반환하는 함수 `promisify(f)`를 만들어봅시다.
6344

@@ -68,21 +49,6 @@ function promisify(f) {
6849
return function (...args) { // 래퍼 함수를 반환함
6950
return new Promise((resolve, reject) => {
7051
function callback(err, result) { // f에 사용할 커스텀 콜백
71-
=======
72-
As we can see, the new function is a wrapper around the original `loadScript` function. It calls it providing its own callback that translates to promise `resolve/reject`.
73-
74-
Now `loadScriptPromise` fits well in promise-based code. If we like promises more than callbacks (and soon we'll see more reasons for that), then we will use it instead.
75-
76-
In practice we may need to promisify more than one function, so it makes sense to use a helper.
77-
78-
We'll call it `promisify(f)`: it accepts a to-promisify function `f` and returns a wrapper function.
79-
80-
```js
81-
function promisify(f) {
82-
return function (...args) { // return a wrapper-function (*)
83-
return new Promise((resolve, reject) => {
84-
function callback(err, result) { // our custom callback for f (**)
85-
>>>>>>> upstream/master
8652
if (err) {
8753
reject(err);
8854
} else {
@@ -102,26 +68,11 @@ let loadScriptPromise = promisify(loadScript);
10268
loadScriptPromise(...).then(...);
10369
```
10470

105-
<<<<<<< HEAD
10671
위 예시는 프라미스화 할 함수가 인수가 두 개(`(err, result)`)인 콜백을 받을 것이라 가정하고 작성되었습니다. 십중팔구 이런 상황일 것이고, 커스텀 콜백은 이 상황에 딱 들어맞습니다. `promisify`가 잘 동작하는 것은 말할 것도 없겠죠.
107-
=======
108-
The code may look a bit complex, but it's essentially the same that we wrote above, while promisifying `loadScript` function.
109-
110-
A call to `promisify(f)` returns a wrapper around `f` `(*)`. That wrapper returns a promise and forwards the call to the original `f`, tracking the result in the custom callback `(**)`.
111-
112-
Here, `promisify` assumes that the original function expects a callback with exactly 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.
113-
>>>>>>> upstream/master
11472

11573
그런데 함수 `f`가 두 개를 초과하는 인수를 가진 콜백, `callback(err, res1, res2, ...)`을 받는다면 어떤 일이 발생할까요?
11674

117-
<<<<<<< HEAD
11875
이런 경우를 대비하여 좀 더 진화한 헬퍼 함수, `promisify`를 만들어 봅시다. 새롭게 만든 함수를 `promisify(f, true)`형태로 호출하면, 프라미스 결과는 콜백의 성공 케이스(`results`)를 담은 배열, `[res1, res2, ...]`이 됩니다.
119-
=======
120-
We can improve our helper. Let's make a more advanced version of `promisify`.
121-
122-
- When called as `promisify(f)` it should work similar to the version above.
123-
- When called as `promisify(f, true)`, it should return the promise that resolves with the array of callback results. That's exactly for callbacks with many arguments.
124-
>>>>>>> upstream/master
12576

12677
```js
12778
// 콜백의 성공 결과를 담은 배열을 얻게 해주는 promisify(f, true)
@@ -149,22 +100,12 @@ f = promisify(f, true);
149100
f(...).then(arrayOfResults => ..., err => ...);
150101
```
151102
152-
<<<<<<< HEAD
153103
`callback(result)`같이 `err`이 없는 형태나 지금까지 언급하지 않은 형태의 이색적인 콜백도 있을 수 있는데, 이런 경우엔 헬퍼 함수를 사용하지 않고 직접 프라미스화 하면 됩니다.
154-
=======
155-
As you can see it's essentially the same as above, but `resolve` is called with only one or all arguments depending on whether `manyArgs` is truthy.
156-
157-
For more exotic callback formats, like those without `err` at all: `callback(result)`, we can promisify such functions manually without using the helper.
158-
>>>>>>> upstream/master
159104
160105
본 챕터에서 설명한 헬퍼 함수보다 더 유용한 형태의 프라미스화를 도와주는 함수를 제공하는 모듈도 많습니다. [es6-promisify](https://github.com/digitaldesignlabs/es6-promisify)가 대표적인 예입니다. Node.js에선 내장 함수 `util.promisify`를 사용해 프라미스화를 할 수 있습니다.
161106
162107
```smart
163-
<<<<<<< HEAD
164108
프라미스화는 곧 배우게 될 `async/await`와 함께 사용하면 더 좋습니다. 다만, 콜백을 완전히 대체하지는 못한다는 사실을 기억해 두시기 바랍니다.
165-
=======
166-
Promisification is a great approach, especially when you use `async/await` (covered later in the chapter <info:async-await>), but not a total replacement for callbacks.
167-
>>>>>>> upstream/master
168109

169110
프라미스는 하나의 결과만 가질 수 있지만, 콜백은 여러 번 호출할 수 있기 때문입니다.
170111

0 commit comments

Comments
 (0)