지영이의 개발 블로그

[자바스크립트]비동기 처리의 시작 콜백 (Callback) 본문

Javascript

[자바스크립트]비동기 처리의 시작 콜백 (Callback)

이지영 2022. 6. 19. 19:50

동기와 비동기

자바스크립트는 동기적(synchronous)이다 

즉 호이스팅이 된 이후부터 우리가 작성한 코드의 순서에 맞게 하나씩 동기적으로 실행된다는 뜻

 

호이스팅이란? var,function declaration 이런 함수 선언들이 자동적으로 젤 위로 호이스팅 되는것이다

동기적(Synchronous)이란?정해진 순서에 맞게 코드가 실행

비동기적(Asynchronous) 이란?언제코드가 실행될지 예측할 수 없는 것을 말한다 

console.log('1')
setTimeout(()=>   //대표적인 비동기적 실행방법,우리가 지정한 시간이 지나면 전달한 콜백함수를 호출
console.log('2'),1000);
console.log('3')

//출력결과 : 1 3 2 순서로 출력

<동기적(Synchronous) callback>

 

console.log('1')
setTimeout(()=> console.log('2'),1000);
console.log('3')


function printImmediately(print){
 	print();
}

 printImmediately(()=>console.log('hello'));
 
 //출력결과 : 1 3 hello 2 순서로 출력

<비동기적(Asynchronous) callback>

console.log('1')
setTimeout(()=> console.log('2'),1000);
console.log('3')

//Synchronous callback
function printImmediately(print){
 	print();
}
printImmediately(()=>console.log('hello'));
 
//Asynchronous callback
 function printWithDelay(print,timeout){
 	setTimeout(print,timeout);
 }
 printWithDelay(()=>
 console.log('async callback'),2000);
 
 
 
 //출력결과 : 1   3   hello   async callback 순서로 출력

콜백이란 이러한 상황처럼 다른 코드가 특정코드가 마무리되기 전에 실행되지 않도록, 즉 비동기처리를 위한 방법이다.

 

-실행순서-

 

콜백지옥

비동기 처리에 콜백함수를 이용하게 되면 비동기 처리를 중첩시켜서 코드를 작성하기때문에 에러, 예외처리가 어렵고 중첩으로 인한 복잡도가 증가하게 된다.

 

웹서비스를 개발하는 경우 서버에서 데이터를 받아오고 화면에 표시하기까지 수많은 비동기 처리를 하게되면서 위와같은 콜백지옥 현상이 나타나게된다.

 

try {
setTimeout(() => { throw 'Error!'; }, 1000);
} catch (e) {
console.log(e);
}

setTime() 함수의 콜백은 콜백큐에 있다가 콜스택이 비어지면 실행되기 때문에 위의 예시의 경우 에러를 캐치하지 못한다. 콜백함수의 중첩은 이처럼 에러처리가 힘들다.

 

이렇게 되면 1. 가독성이 떨어지고 2.디버깅이 매우 어려워진다.
즉 이러한 콜백 지옥에 빠지는 걸 방지하기 위해 나타난 것이 promise 이다.

 

 

프로미스 관련 글 👉https://jssq2468.tistory.com/manage/posts/

 

TISTORY

나를 표현하는 블로그를 만들어보세요.

www.tistory.com

 

Comments