콜백지옥이란?
1. 콜백지옥은 비동기 처리 로직을 위해 콜백 함수를 연속해서 사용할 때 발생하는 문제이다.
2. 콜백함수를 이용해서 비동기 로직처리 시, 코드가 깊어지는 것을 말한다.
3. 일반적으로 콜백지옥을 해결하는 방법에는 Promise 나 async & await를 사용하는 방법이 있다.
콜백지옥 -> Promise -> async & await 순서로 수정한다.
콜백지옥 예시 코드)
class UserStorage{
loginUser(id, password, onSuccess, onError){
setTimeout(() =>{
if(
id === 'kfdd6630' && password === '123'
) {
onSuccess(id);
} else{
onError(new Error('error'));
}
}, 2000);
}
getRoles(user, onSuccess, onError){
setTimeout(()=> {
if (user === 'kfdd6630') {
onSuccess({name: 'kfdd6630', role: 'admin'});
} else {
onError(new Error('error'));
}
}, 1000);
}
};
const userStorage = new UserStorage();
const id = prompt('아이디를 입력해 주세요!');
const password = prompt('비밀번호를 입력해 주세요!!');
userStorage.loginUser(
id,
password,
user => {
userStorage.getRoles(
user,
userWithRole => {
alert(`hello ${userWithRole.name}, you have a ${userWithRole.role} role`)
},
error => {
console.log('에러 02 발생')
}
);
},
error => {console.log('에러 01 발생')}
);
사용자의 id 와 pw를 입력받아 유저정보(role)을 받아와서 출력하는 코드이다.
콜백함수란?
2023.03.21 - [언어/Javascript,TypeScript] - [js] 콜백함수(callback)
[js] 콜백함수(callback)
콜백함수란? 콜백함수를 매개변수로 받는 함수 만드는 방법, 콜백지옥이란? 콜백함수(Callback function)란? 1. 콜백함수는 다른 함수에 매개변수로 넘겨준 함수를 말한다. (함수에 파라미터로 들어가
kfdd6630.tistory.com
1. Promise 적용하기
class UserStorage{
loginUser(id, password){
return new Promise((resolve, reject) => {
setTimeout(() =>{
if(
id === 'kfdd6630' && password === '123'
) {
resolve(id);
} else{
reject(new Error('에러 01 발생'));
}
}, 2000);
})
}
getRoles(user){
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (user === 'kfdd6630') {
resolve({name: 'kfdd6630', role: 'admin'});
} else {
reject(new Error('에러 02 발생'));
}
}, 1000);
})
}
};
const userStorage = new UserStorage();
const id = prompt('아이디를 입력해 주세요!');
const password = prompt('비밀번호를 입력해 주세요!!');
userStorage.loginUser(id, password)
.then(userStorage.getRoles)
// .then(user => userStorage.getRoles(user)); 인자가 하나이고 똑같으니 생략 가능하다.
.then(user => alert(`hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);
Promise란?
2023.03.22 - [언어/Javascript,TypeScript] - [js] Promise 정리
[js] Promise 정리
Promise정리 [ State, Producer, Consumer(then, catch, finally), Promise Chaining, Error Handling ] Promise란? 1. Promise는 비동기 작업에 대한 javascript 개체이다. 2. Promise는 State라는 상태값을 가지고 Promise 생상부분과 사
kfdd6630.tistory.com
2. async & await 적용하기
class UserStorage{
loginUser(id, password){
return new Promise((resolve, reject) => {
setTimeout(() => {
if(
id === 'kfdd6630' && password === '123'
) {
resolve(id);
} else{
reject(new Error('에러 01 발생'));
}
}, 2000);
})
}
getRoles(user){
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (user === 'kfdd6630') {
resolve({name: 'kfdd6630', role: 'admin'});
} else {
reject(new Error('에러 02 발생'));
}
}, 1000);
})
}
};
const userStorage = new UserStorage();
const id = prompt("아이디를 입력해 주세요!");
const password = prompt("비밀번호를 입력해 주세요!!");
async function checkUser() {
try {
const userId = await userStorage.loginUser(id, password);
const user = await userStorage.getRoles(userId);
alert(`Hello ${user.name}, you have a ${user.role}`);
} catch (error) {
console.log(error);
}
}
checkUser();
async & await란?
2023.03.22 - [언어/Javascript,TypeScript] - [js] async & await 정리
[js] async & await 정리
async & await 사용방법, useFul Promise APIs(Promise.all(), Promise.race()) async & await란? 1. async와 await는 자바스크립트의 비동기 처리 패턴 중 가장 최근에 나온 문법이다. 2. 비동기 방식을 사용함에 있어 Promise
kfdd6630.tistory.com
setTimeout은 Promise반환을 하지 않기 때문에 async와 await를 적용해도 동기적으로 적용되지 않는다.
따라서 Promise를 반환하게 직접 작성 후 async와 await를 적용해야 하고 try...catch구문으로 예외처리를 해준다.
2023.03.23 - [언어/Javascript,TypeScript] - [js] try...catch, finally 정리
[js] try...catch, finally 정리
try...catch문, finally 블록 정리 1. try...catch문이란? 실행할 코드블럭을 표시하고 예외(exception)가 발생(throw)할 경우의 응답을 지정한다. try { // 수행하고싶은 로직을 수행한다. doSomething(); } catch (error)
kfdd6630.tistory.com
'언어 > Javascript, Typescript' 카테고리의 다른 글
[js] Dayjs 라이브러리 (설치방법, i18n, 객체생성, get(), set(), DateFormat 설정 등) (0) | 2023.03.24 |
---|---|
[js] 자바스크립트 Date객체 (기간 조회 및 날짜 계산) (0) | 2023.03.24 |
[js] try...catch, finally 정리 (0) | 2023.03.23 |
[js] async & await 정리 (0) | 2023.03.22 |
[js] Promise 정리 (0) | 2023.03.22 |
댓글