개발 지식, 슀크립트/JavaScript, TS

Promise- 후속 μ²˜λ¦¬μ™€ 체이닝(Chaining)

μ‹œνλ¦¬ν‹°μ§€ν˜Έ 2023. 12. 10. 17:54

비동기 처리 μˆ˜ν–‰ 결과에 λ”°λ₯Έ 후속 처리

resolve / reject μ½œλ°±μ— μ˜ν•΄ ν”„λ‘œλ―ΈμŠ€μ˜ 비동기 처리 μƒνƒœκ°€ λ³€ν™”ν•˜λ©΄ (pending -> fullfilled)

후속 처리λ₯Ό μˆ˜ν–‰ν•  μ½”λ“œλ₯Ό μž‘μ„±ν•΄μ•Ό ν•˜λŠ”λ° Promise κ°μ²΄λŠ” κ·ΈλŸ¬ν•œ μ½”λ“œ μž‘μ„±μ„ ν•  수 μžˆλŠ” λ³„λ„μ˜ λ©”μ†Œλ“œλ₯Ό μ œκ³΅ν•œλ‹€.

 

then() , catch(), finally()

*후속 처리: 응닡 κ²°κ³Ό κ°’ μΆ”μΆœ or μ‚¬μš©

 

1. then(callback) - 비동기 처리 성곡 μ‹œ 호좜

비동기 μ²˜λ¦¬κ°€ μ„±κ³΅ν•˜μ—¬ resolve 콜백이 ν˜ΈμΆœλ˜μ—ˆμ„ 경우 λ™μž‘ν•˜λ©°, μ‹€μ œ λ™μž‘ν•˜λŠ” 것은 then() 이 μ•„λ‹Œ then(callback) ν•¨μˆ˜μ˜ 인수둜 μ „λ‹¬λœ 콜백 ν•¨μˆ˜μ΄λ‹€.

1
2
3
const myPromise = new Promise(executor);
myPromise.then((response) => console.log(\`응닡 κ²°κ³Ό: ${response}\`)); 
// μ‘λ‹΅ κ²°κ³Ό: some data
cs

 

2. catch(callback) - 비동기 처리 μ‹€νŒ¨ μ‹œ 호좜

비동기 μ²˜λ¦¬κ°€ μ‹€νŒ¨ν•˜μ—¬ reject 콜백이 ν˜ΈμΆœλ˜μ—ˆμ„ 경우 λ™μž‘ν•˜λŠ” ν•¨μˆ˜

1
2
3
4
5
6
const myPromise = new Promise(executor);
 
myPromise
.then((response) => console.log(\`응닡 κ²°κ³Ό: ${response}\`))
.catch((error) => console.error(\`error: ${error}\`));
// error: μ‘λ‹΅ μ‹€νŒ¨
cs

 

3. finally(callback)

비동기 처리 성곡/μ‹€νŒ¨ 여뢀와 상관없이 λ§ˆμ§€λ§‰μ— ν•œ λ²ˆμ€ 무쑰건 λ™μž‘ν•˜λ„λ‘ 보μž₯λ˜λŠ” ν•¨μˆ˜

1
2
3
4
5
6
7
8
const myPromise = new Promise(executor);
 
myPromise
.then((response) => console.log(\`응닡 κ²°κ³Ό: ${response}\`))
.catch((error) => console.error(\`error: ${error}\`));
.finally(() => console.log('μš”μ²­ μˆ˜ν–‰ μ™„λ£Œ'));
// μ‘λ‹΅ κ²°κ³Ό: some data or error: μ‘λ‹΅ μ‹€νŒ¨
// μš”μ²­ μˆ˜ν–‰ μ™„λ£Œ(무쑰건 ν•œ λ²ˆμ€ λ™μž‘)
cs

 

ν”„λ‘œλ―ΈμŠ€ 체이닝

μ•„λž˜μ™€ 같이 각각의 후속 처리 λ©”μ„œλ“œλ“€μ΄ μ΄μ–΄μ„œ ν˜ΈμΆœν•  수 μžˆλ„λ‘ λ™μž‘ν•˜λŠ” μ΄μœ λŠ” ν•΄λ‹Ή λ©”μ†Œλ“œλ“€μ΄ Promise 객체λ₯Ό λ°˜ν™˜ν•˜κΈ° λ•Œλ¬Έμ΄λ‹€.

1
2
3
4
5
6
7
8
onst myPromise = new Promise(executor);
 
myPromise
.then((response) => console.log(\`응닡 κ²°κ³Ό: ${response}\`))
.catch((error) => console.error(\`error: ${error}\`));
.finally(() => console.log('μš”μ²­ μˆ˜ν–‰ μ™„λ£Œ'));
// μ‘λ‹΅ κ²°κ³Ό: some data or error: μ‘λ‹΅ μ‹€νŒ¨
// μš”μ²­ μˆ˜ν–‰ μ™„λ£Œ(무쑰건 ν•œ λ²ˆμ€ λ™μž‘)
cs

 

ν”„λ‘œλ―ΈμŠ€ 체이닝을 ν™œμš©ν•˜μ—¬ 콜백 ν—¬ κ°œμ„ 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
onst url = '[https://jsonplaceholder.typicode.com'](https://jsonplaceholder.typicode.com');
const promiseGet = url => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.send();
        xhr.onload = () => {
            if (xhr.status === 200) {
                // μ‘λ‹΅ μ„±κ³΅
                resolve(JSON.parse(xhr.response));
            } else {
                // μ—λŸ¬ μ²˜λ¦¬
                reject(new Error(xhr.status));
            }
        };
    });
};
 
promiseGet(\`${url}/posts/1\`) // post idκ°€ 1번인 post μ‘°νšŒ
    .then((user) => promiseGet(\`${url}/users/${user.userId}\`)) // ν•΄λ‹Ή postλ₯Ό μž‘μ„±ν•œ user의 idλ₯Ό μ΄μš©ν•˜μ—¬ user μ •보 μ‘°νšŒ
    .then(userInfo => console.log(userInfo))
    .catch(error => console.error(error));
cs

-> then() 을 톡해 λ³„λ„μ˜ λ“€μ—¬μ“°κΈ° 없이 μ—°μ†μ μœΌλ‘œ 비동기 처리 μˆ˜ν–‰ κ°€λŠ₯

 

catch(callback)을 톡해 μ—λŸ¬μ²˜λ¦¬κ°€ κ°€λŠ₯ν•˜λ‹€.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const url = '[https://jsonplaceholder.typicode.com'](https://jsonplaceholder.typicode.com');
const promiseGet = url => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.send();
        xhr.onload = () => {
            if (xhr.status === 200) {
                // μ‘λ‹΅ μ„±κ³΅
                resolve(JSON.parse(xhr.response));
            } else {
                // μ—λŸ¬ μ²˜λ¦¬
                reject(new Error(xhr.status));
            }
        };
    });
};
promiseGet(\`${url}/xxx/1\`) // μœ νš¨ν•˜μ§€ μ•Šμ€ url둜 μ‘°νšŒ μš”μ²­
    .then((user) => console.log(user))
   // .then(λ‹€λ₯Έ λΉ„동기 μ²˜λ¦¬ μ½”λ“œ) ...
    .catch(error => console.error(error));
cs