Frontend/Javascript

Promise란?

간지나제 2021. 3. 9. 20:25

한 마디로 비동기 통신에서 사용하는 객체라고 할 수 있다.
전에는 call back함수로 데이터를 받았다면

ex)

// 서버에서 받은 데이터 response를 callbackFunc() 함수에 넘겨줌  
function  getData(callbackFunc) {
    $.get('url 주소/products/1', function(response) {
        callbackFunc(response);
    });  
}
// $.get()의 response 값이 tableData에 전달됨  
getData(function(tableData) {
    console.log(tableData); 
});

이렇게 되면 흔히들 말하는 call back지옥에 빠지기도 쉽고
개인적으로 한 눈에 와닿기가 쉽지않다.

이후에 나온게 Promise객체인데
ex)

// 데이터를 받으면 resolve() 호출
function getData() {
    return new Promise(function(resolve, reject) {
        $.get('url 주소/products/1',function(response) {
            resolve(response);
        });
    }
} // getData()의 실행이 끝나면 호출되는 then()

// resolve()의 결과 값이 여기로 전달됨
getData().then(function(tableData) { 
    console.log(tableData); // $.get()의 reponse 값이 tableData에 전달됨
});

mdn에서 promise에 대해서 자세히 더 볼 수 있음.
프로미스 상태(pending, fulfill, reject)의 상태가 있고 마지막에 Prmoise 객체를 return 한다.
then or catch를 사용하여 활용할 수 있다.

프로미스 에러처리하는 방법은
then(func1, func2) => func2로 에러처리를 할 수 있는 함수를 활용할 수도 있고 catch를 활용해서 에러처리를 할 수 있다.
가급적 catch를 사용한다.
promise가 기본이 되긴 하지만 역시나 promise보다는 es6에서부터 사용하는 async await가 훨씬 보기편하다.


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