1. 동기 VS 비동기
- 동기(Synchronous) 요청 : 작업이 순차적으로 진행됨
- 비동기(Asynchronous) 요청 : 작업이 독립적으로 실행 됨
= 작업의 완료 여부를 기자리지 않도 다른 작업을 실행
2. 비동기 요청(in JavaScipt)
- fetch( "요청 경로", {속성} ).then().then 사용
fetch("/email/signup", {
method : "POST",
headers : {"Content-Type" : "application/json"},
body : memberEmail.value
})
.then(resp => resp.text())
.then(result => {
if(result == 1){
console.log("인증 번호 발송 성공");
} else {
console.log("인증 번호 발송 실패!!!!");
}
});
3. submit 요청(비동기 요청) 중 동기 요청 사용
3-1) async,await 사용
- async : 비동기 함수를 만들 때 사용하는 키워드
= ("이 함수 내에는 오래 걸리는 작업이 있어요!")
- await : 비동기 작업의 결과를 기다릴 때 사용 -> !!! 반드시 async 함수 안에서만 사용 가능
= "이 작업이 끝날때까지 기다려주세요"
3-2) 예시
example.addEventListrner("submit", async (e) => {
e.preventDefault();
...
const asyncExample = await fetch("요청 주소");
const awaitExample = asyncExmample.text();
...
example.submit();
}
3-3) 설명
- e.prevebtDefault() : 이벤트가 발생하지 않도록 미리 막아둠
- .submit() : 문제 없이 함수(exmaple)의 끝에 닿았을 때 이벤트가 발생 할 수 있도록 해 줌