JavaScript/JavaScript 기본

프로미스

검정비니 2018. 8. 6. 23:51
728x90
반응형

프로미스




자바스크립트와 node.js에서는 주로 비동기 프로그래밍을 한다. 특히 이벤트 구조 방식 때문에 콜백 함수를 자주 사용한다. 


ES2015부터는 자바스크립트와 node.js의 API들이 콜백 대신 프로미스(promise) 기반으로 재구성된다. 그래서 악명 높은 콜백 지옥(callback hell)을 극복했다는 평가를 받고 있다.


프로미스를 사용하려면 먼저 프로미스 객체를 생성해야 한다.


i.e.

const promise = new Promise( (resolve, reject) => {

if(조건문) {

resolve('success');

} else {

reject('failed');

}

});


promise

.then((message) => {

console.log(message);

})

.catch((error) => {

console.error(error);

});



new Promise()로 프로미스를 생성할 수 있으며, 안에 resolve와 reject를 매개 변수로 갖는 콜백 함수를 넣어준다. 이렇게 만든 promise 변수에 then과 catch 메소드를 붙일 수 있다. 프로미스 내부에서 resolve가 호출되면 then이 실행되고, reject가 호출되면 catch가 실행된다.


resolve와 reject에 넣어준 인자는 각각 then과 catch의 매개 변수에서 받을 수 있다. 즉, 위의 코드에서는 message가 'success'이고, error가 'failed'가 된다.


또한, then이나 catch에서 다시 다른 then이나 catch를 붙일 수 있다. 이 경우, 이전 then의 return 값을 다음 then의 매개 변수로 넘긴다. 프로미스를 리턴한 경우, 프로미스가 수행된 후 다음 then이나 catch가 호출된다.


i.e.

promise

.then((message) => {

return new Promise((resolve, reject) => {

resolve(message);

};

})

.then((message2) => {

return new Promise((resolve, reject) => {

resolve(message2);

};

})

.then((message3) => {

console.log(message3);

})

.catch ((error) => {

console.error(error);

});



위의 코드처럼 then이나 catch의 연속을 통해서 콜백을 프로미스로 대체할 수 있다.

반응형