Javascript/비동기 처리

Promise - then & catch

appmaster 2021. 1. 26. 18:07

 비동기적인 상황에서 코드를 좀 더 명확하게 표현하고 실행하도록 만들 수 있다.

 

1. ES6 부터 Javascript의 표준 내장 객체로 추가 되었다.

ES6 를 지원하는 브라우저나 Node.js 에서 전역에 있는 Promise 를 확인할 수 있다.

 

 

2. 생성자를 통해서 프로미스 객체를 만들 수 있다.

생성자의 인자로 executor 라는 함수를 이용한다.

 

 

3. executor 함수는 resolve 와 rejcect를 인자로 가진다. 

(resolve, reject) -> {...}

resolve 와 reject는 함수이다.

resolve(), reject()

 

 

4. 생성자를 통해서 프로미스 객체를 만드는 순간 pending(대기) 상태라고 한다.

 

 

5. executor 함수 인자 중 하나인 resolve 함수를 실행하면, fulfilled (이행) 상태가 된다.

 

 

6. executor 함수 인자 중 하나인 reject 함수를 실행하면, rejected (거부) 상태가 된다.

 

 

 

ex) p라는 프로미스 객체는 1000ms 후에 fulfilled 된다.

new Promise ((resolve, reject)=>{
    /* pending */
    setTimeout(()=>{
        resolve(); /* fulfilled */
    }, 1000)
})

 

 

ex) p라는 객체가 fullfiled 되는 시점에 p.then 안에 설정한 callback 함수가 실행된다.

const p = new Promise ((resolve, reject)=>{
    /* pending */
    setTimeout(()=>{
        resolve(); /* fulfilled */
    }, 1000);
});

p.then(()=>{
    /* call back이 작성이 되는 구간 */
})

 

 

ex) then을 설정하는 시점을 정확히 하고, 함수의 실행과 동시에 프로미스 객체를 만들면서 pending이 시작하도록 하기 위해 프로미스 객체를 생성하면서 리턴하는 함수(p) 를 만들어 함수 (p) 실행과 동시에 then을 설정한다.

function p(){
    return new Promise ((resolve, reject)=>{
        /* pending */
        setTimeout(()=>{
            resolve(); /* fulfilled */
        }, 1000);
    });
}


p().then(()=>{
    console.log('1000ms 후에 fullfiled 된다.');
});

 

 

ex) 마찬가지로 프로미스 객체가 rejected 되는 시점에 p.catch 안에 설정한 callback 함수가 실행된다.

function p(){
    return new Promise ((resolve, reject)=>{
        /* pending */
        setTimeout(()=>{
            reject(); /* fulfilled */
        }, 1000);
    });
}


p()
.then(()=>{
    console.log('1000ms 후에 fullfiled 된다.');
})
.catch(()=>{
    console.log('1000ms 후에 rejected 된다.');
});

이렇게 비동기함수가 성공적으로 실행했을 때와, 임무를 진행하다가 무언가가 잘못되어서 상태의 차이가 생길때는 반드시 표시를 해줘야한다.

 

 

ex) executor의 resolve 함수를 실행할때 인자를 넣어 실행하면, then의 callback 함수의 인자로 받을 수 있다. 

resolve('hello'); then((message)=>{...}) **자주쓰는내용!

function p(){
    return new Promise ((resolve, reject)=>{
        /* pending */
        setTimeout(()=>{
            resolve('hello'); /* fulfilled */
        }, 1000);
    });
}


p()
.then((message)=>{
    console.log('1000ms 후에 fullfiled 된다.', message);
})
.catch(()=>{
    console.log('1000ms 후에 rejected 된다.');
});
//출력값
1000ms 후에 fullfiled 된다. hello

보통 이것은 원격으로 데이터를 가져올때 많이 사용한다. 원격으로 요청 하고 정상적으로 받았을때 그 받아온 데이터를 then으로 데이터를 넘겨서 주고 그것을 활용하는 용도로 많이 사용한다.

 

 

 

ex) 마찬가지로, executor의 reject 함수를 실행할때 인자를 넣어 실행하면, catch의 callback 함수의 인자로 받을 수 있다. reject('error'); then((reason)=>{...})

function p(){
    return new Promise ((resolve, reject)=>{
        /* pending */
        setTimeout(()=>{
            reject(new Error('bad')); /* fulfilled */
        }, 1000);
    });
}


p()
.then((message)=>{
    console.log('1000ms 후에 fullfiled 된다.', message);
})
.catch((error)=>{
    console.log('1000ms 후에 rejected 된다.', error);
});
//출력값
1000ms 후에 rejected 된다. Error: bad
    at <anonymous>:5:20

이것도 앞으로 많이하게될 작업이다.