Project/개인프로젝트

자바 스크립트 fetch, await, async

Sol b 2023. 12. 3. 15:06

fetch() 를 이용하면 url을 통해 원하는 API의 결과값을 받아올 수 있습니다.

그런데 js는 인터프립터 언어이기때문에 fetch를 사용하게되면 null을 반환하게 됩니다.

let resopnse = fetch("http://localhost:8080/chat", {
	method: "post",
	body: JSON.stringify(chat), // JS -> JSON
	headers: {
		"Content-Type": "application/json; charset=utf-8"
	}
});

 

이때 바로 변수에 값을 할당하지 않고 fetch의 반환값이 올때까지 기다렸다

변수에 대응하게 값을 할당하는 것이 awit입니다.

즉, 통신이 끝날때까지 기다리게 됩니다.

 

awit 적용 후

let resopnse = await fetch("http://localhost:8080/chat", {
	method: "post",
	body: JSON.stringify(chat), // JS -> JSON
	headers: {
		"Content-Type": "application/json; charset=utf-8"
	}
});

 

하지만 이렇게되면 함수 자체가 멈추게 됩니다.

fetch의 응답을 받을때까지 아무것도 하지 못하게 되는것입니다.

 

이런 상황은 함수에 async를 적용하여 비동기 호출을 하게되면 해결됩니다.

async는 비동기 호출을 담당합니다.

// AJAX 채팅 메시지를 전송
async function addMessage() {
	let msgInput = document.querySelector("#chat-outgoing-msg");

	let chat = {
		sender: username,
		roomNum: roomNum,
		msg: msgInput.value
	};

	fetch("http://localhost:8080/chat", {
		method: "post", //http post 메서드 (새로운 데이터를 write)
		body: JSON.stringify(chat), // JS -> JSON
		headers: {
			"Content-Type": "application/json; charset=utf-8"
		}
	});

	msgInput.value = "";
}