반응형
fetch 함수 실행
console.log('START!');
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.text())
.then((result) => {console.log(result); })
console.log('END');
결과
START!
END
[
{
"id": 1,
...
→ response 내용이 END 보다 늦게 출력 됨
- 처음 START 출력
- request 보냄. then 메소드는 callback 함수를 등록할 뿐, 실행하지 않음.
- 그리고 다음 End 출력
- 서버로부터 response가 도착하고, then 메소드로 등록된 callback들이 실행됨(비동기 실행).
- 동기 실행: 한 번 시작한 작업은 다 처리하고 나서 다음 코드로 넘어감.
비동기 실행 장점
- 동일한 작업을 더 빠른 시간 내에 처리 할 수 있음.
- 동기 실행은 fetch 함수 실행 하면 response가 올 때까지 기다려야 함(아무런 작업을 못 함).
비동기 함수 예제
1. setTimeout
- callback 시간을 특정 시간 만큼 미룸
console.log('a');
setTimeout(() => { console.log('b'); }, 2000);
console.log('c');
결과
a
c
b
2. setInterval
- callback을 특정 시간마다 실행
console.log('a');
setInterval(() => { console.log('b'); }, 2000);
console.log('c');
3. addEventListener
btn.addEventListener('click', (e) => {
console.log('Hello Codeit!');
});
반응형