비동기 처리 - Promise

2020. 6. 16. 13:26웹/Javascript(ES6+)

개요

  • 전통적인 자바스크립트의 비동기 처리를 위한 패턴으로 콜백함수가 존재

  • 콜백함수의 경우, 가독성 및 에러의 예외처리 한계

  • ES6 Promise 등장하여 단점 보완

 

정의

  • Promise는 비동기 작업의 최종 완료 또는 실패를 나타내는 객체

  • Promise는 함수에 콜백을 전달하는 대신, 콜백을 첨부하는 방식의 객체

 

특징

  • 콜백은 자바스크립트 Event Loop 가 현재 실행중인 콜 스택을 완료하기 전에는 절대 호출 되지않음

  • then() 을 여러번 사용하여 여러개의 콜백 추가 가능(chaning), 순서대로 콜백이 수행

 

예제) 

// Promise 객체 생성
const fetchData = new Promise((resolve, reject) => {
        // 비동기 작업 수행, setTimeout으로 대체
        setTimeout(() => {
            // 비동기 작업 수행 성공, 실패 시 reject 수행
           reslove();
        }, 500);
    });
}

fetchData.then((result) => {
    // resolve() 의 결과 값(result)이 여기로 전달    console.log(result);
});

 

 

 

Promise 3가지 상태(states)

  • Pending(대기)    : 비동기 처리 로직이 아직 완료되지 않은 상태

  • Fullfilled(이행) : 비동기 처리가 완료되어 프로미스 결과 값을 반환해준 상태

  • Rejected(실패)   : 비동기 처리가 실패하거나 오류가 발생한 상태

 

Pending(대기)

  • new Promise() 메서드를 호출하면 Pending 상태가 됨

new Promise();

 

Fullfilled(이행)

  • 콜백 함수 인자인 resolve 를 실행 시 Fullfilled 상태가 됨

const fetchData = new Promise((resolve, reject) => {
    const result = 'test';
    resolve(result);
});

fetchData.then((result) => {
    // resolve 결과 값을 전달 받을 수 있음
    console.log(result);  // test
});

 

Rejected(실퍠)

  • 콜백 함수 인자인 reject 를 실행 시 Rejected 상태가 됨

const fetchData = new Promise((resolve, reject) => {
    reject();
});

// 실패 처리 결과를 catch 를 통해 제어
fetchData.then().catch((error) => {
    console.log(error);
});

 

 

 

Promise Chaning

  • 두개 이상의 비동기 작업을 순차적으로 실행하는 상황에서 Promise Chain을 이용

const promise  = fetchData();
const promise2 = fetchData().then(successCallback, failureCallback);

 

예제) 예전 방식

fetchData(function(result) {
    fetchData2(result, function(result2) {
        fetchData3(result2, function(result3) {    
            ...
        }, failureCallback);    
    }, failureCallback);
}, failureCallback);

 

예제) Promise Chaining

fetchData().then(result  => fetchData2(result))
           .then(result2 => fetchData3(result2))
           .then(result3 => {
                console.log('...');
            })
           .catch(failureCallback);

 

 

 

 

 

 

 

 

 

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises

https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

 

' > Javascript(ES6+)' 카테고리의 다른 글

비동기 처리 - async & aswait  (0) 2020.06.17
iterator 와 for-of  (0) 2020.04.10
Rest, Spread 연산자  (0) 2020.04.09
Destructuring(구조 분해 할당)  (0) 2020.04.08
템플릿 리터럴 문자열 표현식  (0) 2020.04.08