Promise 객체가 나온 이유
자바스크립트를 공부하던 중 promise 객체를 공부하면서 promise 객체 이전엔 어떤 식으로 비동기 처리를 했고
어떤 문제점 때문에 promise 객체가 나온 이유에 대해 알아보기로 했다.
Promise 객체 이전
promise 객체가 나오기 이전에도 아래 메서드들처럼 비동기 처리를 할 수 있었다.
setTimeout(callback, milliseconds);
addEventListener(eventname, callback);
fetch 함수도 마찬가지로 promise 객체를 반환하지 않았다면 아래처럼 사용했을것이다.
fetch('https://first.com', callback)
만약 promise.then 으로 promise chaining 을 하듯 여러 비동기작업을 순차적으로 처리를 하려면
아래처럼 콜백 헬(callback hell) 이라고 하는 지옥의 피라미드를 만들었을 것이다.
fetch('https://first.com', (response) => {
// Do Something
fetch('https://second.com', (response) => {
// Do Something
fetch('https;//third.com', (response) => {
// Do Something
fetch('https;//fourth.com', (response) => {
// Do Something
});
});
});
});
지금 봐도 지옥같은 가독성에 Do Something 주석 자리에 실제 코드가 들어있었다면 더 끔찍했을 것이라 예상할 수 있다.
Promise 객체 이후
promise 객체가 나온 이후 위와 같은 콜백 헬을 아래처럼 바꿔서 비교적 가독성 높고 깔끔하게 처리할 수 있다.
fetch('https://first.com')
.then((response) => {
// Do Something
return fetch('https://second.com');
})
.then((response) => {
// Do Something
return fetch('https://third.com');
})
.then((response) => {
// Do Something
return fetch('https://third.com');
});
이 뿐 아니라 promise 객체가 제공하는 문법들 덕분에 비동기 작업 처리 시 더 세밀한 처리를 할 수 있게 되었다.
'언어 > JavaScript' 카테고리의 다른 글
[JavaScript] 스코프 체인과 호이스팅 (0) | 2023.12.01 |
---|---|
[JavaScript] 자바스크립트 엔진 개요 (0) | 2023.11.28 |
[JavaScript] async 와 await (0) | 2023.11.04 |
[JavaScript] const 와 불변(immutable) (0) | 2023.10.27 |