Skip to content

Commit ac1b54c

Browse files
authored
chapter 9 (#75)
1 parent 58c25b0 commit ac1b54c

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

챕터_9/우창완.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# 9장 비동기 프로그래밍 패턴
2+
3+
4+
5+
gpt 에 Promise 패턴 몇 개 만들어줘 ~ 입력하고 그래로 복붙한 것 같다.
6+
7+
8+
9+
간혹 callback 함수를 Promise로 래핑하는 경우:
10+
11+
```js
12+
// 기존 레거시 콜백 함수, 이미 여러 함수가 이 함수를 사용하고 있어서 변경할 수 없을 경우
13+
function readFileCallback(filename, callback) {
14+
fs.readFile(filename, 'utf8', (err, data) => {
15+
if (err) {
16+
callback(err, null);
17+
return;
18+
}
19+
const processedData = data.toUpperCase();
20+
callback(null, processedData);
21+
});
22+
}
23+
```
24+
25+
26+
27+
* Promise로 직접 래핑하기
28+
29+
```js
30+
//1. Promise로 직접 래핑
31+
function readFilePromise(filename){
32+
return new Promise((resolve, reject) => {
33+
readFileCallback(filename, (err, data) => {
34+
if(err){
35+
reject(err)
36+
return
37+
}
38+
resolve(data);
39+
})
40+
})
41+
}
42+
```
43+
44+
45+
46+
* promisify 유틸함수 사용
47+
48+
```js
49+
// Promise로 래핑하는 방법 2: 유틸리티 함수 사용
50+
function promisify(fn) {
51+
return function (...args) {
52+
return new Promise((resolve, reject) => {
53+
fn(...args, (err, data) => {
54+
if (err) {
55+
reject(err);
56+
return;
57+
}
58+
resolve(data);
59+
});
60+
});
61+
};
62+
}
63+
64+
// 유틸리티 함수를 사용해서 래핑
65+
const readFilePromisified = promisify(readFileCallback);
66+
```
67+
68+
69+
70+
* node 환경이라면, promisify 딸깍할 수 있다
71+
72+
```js
73+
import { promisify } from "node:util"
74+
75+
const readFilePromisified2 = util.promisify(readFileCallback);
76+
```
77+
78+

0 commit comments

Comments
 (0)