Promise 객체
- JS의 비동기 프로그래밍에서 근간이 되는 기법
- 콜백지옥을 개선하기위해서 등장한 기법
Promise 생성
const PRO = (str, ms) => {
return new Promise((resolve, reject) => {
setTimeout(()=>{
if(str === 'A') {
resolve('성공 : A임');
} else {
reject('실패 : A아님');
}
}, ms);
});
}
Promise 호출
PRO('B' , 5000)
.then(result => console.log('then : ' + result))
.catch(err => console.log('catch : ' + err))
콜백지옥과 개선
setTimeout(() => {
console.log('A');
setTimeout( () => {
console.log('B');
setTimeout(() => {
console.log('C')
}, 1000);
}, 2000);
}, 3000);
const PRO2 = (str, ms) => {
return new Promise( (resolve) => {
setTimeout(() => {
console.log(str);
resolve();
}, ms);
});
}
PRO2('A', 3000)
.then(() => PRO2('B', 2000))
.then(() => PRO2('C', 1000))
.catch(() => console.log('ERROR'))
.finally(() => console.log('파이널리'));
병렬 처리 방법(Promise.all())
const myLoop = cnt => {
for(let i = 0; i < cnt; i++) {
}
console.log('myLoop 종료 : ' + cnt);
}
Promise.all([myLoop(100000000), myLoop(10000000), myLoop(1000000)]);
async/await란?
- Promise 체이닝 또한 연결이 많아 질 경우 코드가 난잡해 질 수 있어
async & await
를 도입
- 코드 작성 부분을 유지보수와 가독성 좋게 해주나, 내부적으로는 Promise를 사용해 비동기 처리를 하므로
Promise
를 대체하는 방법은 아니다.
- function 키워드 앞에
async
키워드를 붙여주고, 비동키 처리되는 부분 앞에 await
키워드를 붙여주어 구현
const PRO2 = (str, ms) => {
return new Promise( (resolve) => {
setTimeout(() => {
console.log(str);
resolve();
}, ms);
});
}
PRO2('A', 3000)
.then(() => PRO2('B', 2000))
.then(() => PRO2('C', 1000))
.catch(() => console.log('ERROR'))
.finally(() => console.log('파이널리'));
const myAsync = async () => {
try {
await PRO2('A', 3000);
await PRO2('B', 3000);
await PRO2('C', 3000);
} catch(err) {
console.log(err);
}
}