promise

Tags

Promise

프로미스는 자바스크립트 안에 내장되어있는 오브젝트.
비동기적으로 처리할 때 콜백함수 대용으로 유용하게 사용할 수 있음.
 

프로미스를 사용하는 이유

네트워크와 상호작용 하는 경우라던지, 파일 입출력 등은 시간이 오래걸리는 작업임.
이러한 작업들을 동기적으로 처리하게 되면, 이전 작업이 끝날 때까지 기다려야하므로 엄청난 시간, 자원 낭비
💡
⇒ 헤비한 작업들은 비동기 처리로 넘기고 이후 작업을 곧바로 실행하자!
 

프로미스의 상태

프로세스가 operation을 수행중인지, 기능 수행이 다 되고 성공/실패 여부
pending → fulfilled or rejected
  • pending : operation 수행 중
  • fulfilled : 성공적으로 완료한 상태
  • rejected : 문제가 발생한 상태
 

Promise

notion image
생성자를 보면 프로미스를 생성하기 위해서는 executor라는 콜백함수를 전달해야 하는데,
executor는 또 2가지의 콜백함수를 인자로 받는다.
  • 기능을 정상적으로 수행해서 마지막으로 최종 데이터를 전달하는 resolve 콜백함수
  • 기능 수행 도중 문제가 생겼을 때 호출할 reject 콜백함수
 

producer, consumer

원하는 기능을 수행해서 필요한 데이터를 만들어 내는 producer ( Promise 오브젝트 )
만들어진 데이터를 소비하는 consumer
 

Producer : 프로미스 객체 생성

notion image
💡
when new Promise is created, the executor runs automatically.
new Promise()를 하는 순간에 바로 executor가 실행된다는 점을 반드시 기억하자 !!
이 사실을 간과한다면, 불필요한 상황에서도 네트워크 처리를 하게 되는 경우가 발생할 수 있음.
const promise = new Promise((resolve, reject)=>{ // 헤비한 작업 수행 (네트워크 작업, 파일 입출력 등) console.log('나는 무언가 하고 있다...'); if( status === '200' ) { // 작업이 정상적으로 완료된 경우 resolve( 'success' ); } else{ // 작업이 제대로 처리되지 않은 경우 reject(new Error('network error'); } }
 

Consumers : then, catch, finally

// 2. Consumers: then, catch, finally promise .then(value => { // resolved 됐을 때 console.log(value); }) .catch(error => { // rejected 됐을 때 console.log(error); }) .finally(() => { // 성공 실패 여부 상관없이 마지막에 무조건 작업을 수행 console.log('finally'); });
 

Promise Chaining

.then, .catch, .finally 모두 promise를 반환하므로 체이닝을 걸 수 있다.
notion image
const fetchNumber = new Promise((resolve, reject) =>{ setTimeout(() => resolve(1), 1000); }); fetchNumber .then(num => num*2) .then(num => num*3) .then(num => { return new Promise((resolve, reject) => { setTimeout(() => resolve(num - 1), 1000); }); }) .then(num => console.log(num));
 

에러 잘 처리하기

reject로 에러가 전달될 때, .catch 구문에서 받아서 적절히 처리하면 됨.
notion image
notion image