본문 바로가기

JavaScript

38. 프로미스(Promise)

프로미스(Promise)

- 자바스크립트 비동기 처리에 사용되는 객체
- 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용

프로미스(Promise) 사용 시 장점

- 비동기 처리 시점을 명확하게 표현
- 연속된 비동기 처리 작업을 수정, 삭제, 추가하기 편하고 유연하게 만듬
- 코드의 유지 보수성이 증가

프로미스(Promise) 문법
const 프로미스객체명 = () => new Promise((resolve, reject) => {

});

- 비동기 처리가 성공 또는 실패 등의 상태 정보를 갖게됨

- resolve가 호출된 경우: 성공
- reject가 호출된 경우: 실패

프로미스(Promise)를 리턴받은 객체

- .then(정상적으로 프로미스 객체가 리턴되었다면 필요한 일을 수행)

- .catch(에러객체가 리턴되었다면 에러를 처리)
- .finally(최종적으로 처리할 일을 수행)

프로미스 예제 1
function runInDelay(seconds) {
    // resolve, reject 콜백으로 값들이 채워짐
    return new Promise((resolve, reject) => {
        if(!seconds || seconds < 0){
            // Error: 자바스크립트에서 에러를 발생시키는 객체
            reject(new Error('seconds가 0보다 작음!'));
        }
        setTimeout(resolve, seconds * 1000);
    })
}
runInDelay(3)
    .then(() => console.log("타이머가 완료되었습니다")) // 성공했을때, 
    .catch(console.error) // 실패했을때, error 출력
    .finally(() => console.log("모든 작업이 끝났습니다"));

3초뒤 console에 출력

runInDelay(-1)
    .then(() => console.log("타이머가 완료되었습니다")) // 성공했을때, 
    .catch(console.error) // 실패했을때, error 출력
    .finally(() => console.log("모든 작업이 끝났습니다"));

오류 발생

프로미스(Promise) 예제 2
function fetchEgg(chicken) {
    return Promise.resolve(`${chicken} => 🥚`);
}

function fryEgg(egg) {
    return Promise.resolve(`${egg} => 🍳`);
}

function getChicken() {
    return Promise.resolve(`🐤 => 🐓`);
    // return Promise.reject(new Error("치킨집 망함"));
}

getChicken()
.then((chicken) => {
    return fetchEgg(chicken);
})
.then((egg) => fryEgg(egg))
.then((friedEgg) => console.log(friedEgg))
.catch(() => '🐥');

// 축약형
getChicken()
.then(fetchEgg)
.then(fryEgg)
.then(console.log)
.catch(() => '🐥');

둘다 동일하게 출력


Promise.all([프로미스객체1, 프로미스객체2, ...])

- 병렬적으로 한번에 모든 promise들을 실행

function getBanana() {
    return new Promise((resolve) =>{
        setTimeout(() => {
            resolve('🍌');
        }, 1000);
    })
}

function getApple() {
    return new Promise((resolve) =>{
        setTimeout(() => {
            resolve('🍎');
        }, 3000);
    })
}

function getOrange() {
    return Promise.reject(new Error("오렌지는 다팔림!"));
}

// Promise.all
// 병렬적으로 한번에 모든 promise들을 실행
// 병렬적으로 처리되기 때문에, 4초가 아닌 3초가 소요됨
Promise.all([getBanana(), getApple()])
    .then((fruits) => console.log('Promise.all: ', fruits));

3초뒤 출력

- 하나라도 실패하면 전체가 실패

// 하나라도 실패하면 전체가 실패
Promise.all([getBanana(), getApple(), getOrange()])
    .then((fruits) => console.log('Error ', fruits))
    .catch(console.log);

Promise.allSettled([프로미스객체1, 프로미스객체2, ...])

- 에러가 발생하더라도 모든 promise들의 결과를 반환

Promise.allSettled([getBanana(), getApple(), getOrange()])
    .then((fruits) => console.log('Promise.allSettled: ', fruits))
    .catch(console.log);

Promise.race([프로미스객체1, 프로미스객체2, ...])
function getBanana() {
    return new Promise((resolve) =>{
        setTimeout(() => {
            resolve('🍌');
        }, 1000);
    })
}

function getApple() {
    return new Promise((resolve) =>{
        setTimeout(() => {
            resolve('🍎');
        }, 3000);
    })
}


Promise.race([getBanana(), getApple()])
    .then((fruit) => console.log('Promise.race: ', fruit))

바나나 1초뒤에 출력

 

'JavaScript' 카테고리의 다른 글

40. async / await  (0) 2023.04.14
39. 옵셔널 체이닝(Opthional Chaining)  (0) 2023.04.14
37. 예외처리  (0) 2023.04.13
36. 맵(map)  (0) 2023.04.13
35. 세트(Set)  (0) 2023.04.13