const f1=(callback) => {
setTimeout(function() {
console.log("1번주문 완료");
callback();
}, 2000);
};
const f2=(callback) => {
setTimeout(function() {
console.log("2번주문 완료");
callback();
},2000);
};
const f3=(callback)=> {
setTimeout(function() {
console.log("3번주문 완료");
callback();
}, 2000);
};
console.log('시작')
f1(function() {
f2(function() {
f3(function() {
console.log("끝")
});
});
});
===> 콜백 지옥에 빠질 수 있으므로 promise로 구현한다
const f1=() => {
return new Promise((res,rej)=> {
setTimeout(()=> {
res("1번 주문완료");
}, 2000);
});
};
const f2=(message) => {
console.log(message);
return new Promise((res,rej)=> {
setTimeout(()=> {
res("2번 주문완료");
}, 3000);
});
};
const f3=(message) => {
console.log(message);
return new Promise((res,rej)=> {
setTimeout(()=> {
res("3번 주문완료");
}, 2000);
});
};
//프로미스 체이닝 (promise chaining)
console.log("시작");
f1()
.then(res=>f2(res))
.then(res=>f3(res))
.then(res=>console.log(res))
.catch(console.log)
.finally(()=>{
console.log("끝"):
});
'JavsScript' 카테고리의 다른 글
Generator ; 함수의 실행을 중간에 멈췄다가 재개할 수 있는 기능 (0) | 2022.10.02 |
---|---|
async await ; 주문할 때 쓰는 (0) | 2022.10.02 |
Promise ; 콜백함수 (0) | 2022.10.02 |
Class ; 생성자 오버라이딩 (0) | 2022.10.02 |
class ; 메소드 오버라이딩 (0) | 2022.10.02 |