자바스크립트를 실행하는 소프트웨어로는 우리가 잘 알고 있는 웹브라우저와 런타임인 Node.js 가 있다
웹브라우저
js(heap,callstack)>webapi>callback queue >eventloop>callstack
만약 webapi를 거치지않는 동기 함수(console.log같은)는 대부분 바로 callstack에서 출력
비동기 함수 (settimeout같은)는 위에 단계를 거쳐 출력
이때 Web APIs는 여러개의 스레드로 구성되어있다.
Callback Queue의 종류
macro task queue setTimeout,fetch,addEventListener 등 으로 작업되는 함수들
micro task queue promise.then,async/await등 으로 작업되는 함수들 <<요놈이 우선순위 높음
예를 들어보자
console.log("1");
setTimeout(function() {
console.log("setTimeout 2");
}, 0);
Promise.resolve().then(function() {
console.log("Promise.then 3");
});
console.log("4");
1.console.log("1") callstack 호출 후 출력
2.콜스택비었으니setTimeout(function() { console.log("setTimeout 2"); }, 0); 에서 webapi를 거쳐 매크로태스크큐로 이동
3.콜스택이 비었으니 Promise.resolve().then(function() { console.log("Promise.then 3"); }); 호출 > webapi > 마이크로태스크큐로 이동
4.콜스택이 비었으니 console.log("4"); 호출 후 출력
5.이젠 진짜 콜스택이 빈것을 확인한 이벤트루프는 마이크로>매크로순으로 함수를 꺼내와서 콜스택에 전달 후 출력
6. "1" "4" "Promise.then 3" "setTimeout 2"
맞는지 모르겟다 ㅠ