fetch
보통 비동기 통신은 AJAX를 많이 사용 했는데 fetch 라는 자바스크립트 본연의 함수를 사용 할 수도 있다.
fetch 는 아래와 같이 사용한다.
fetch(url, options)
첫번째 인자는 url을 받고, 두번째 인자는 옵션을 받는다. (선택)
이 옵션에는 method, header 같은 세부 설정을 할 수 있다. ( 옵션 인자가 없으면 기본 GET 이다. )
//옵션이 없는 경우
fetch("www.xxx.com")
.then(response => response.json())
.catch(error => console.log(error);
//옵션이 있는 경우
fetch("www.xxx.com" , {
method : "POST",
header : {
"Content-Type" : "application/json"
},
body: JSON.stringify({
name : "code-gray"
})
}).then(response => response.json())
.catch(error => console.log(error));
리턴 타입은 promise 타입이다.
promise는 쉽게 설명하면 비동기 처리를 위한 객체인데 비동기를 잘 실행하면 then 처리 실행하지 못하면 catch처리를 할 수 있다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promise - JavaScript | MDN
Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
developer.mozilla.org
즉 fetch도 promise 타입이기 때문에 then , catch로 후처리를 할 수 있다는 이야기다.
async / await
이런 비동기 함수는 async await 코드와 같이 쓰면 더 편하게 사용 가능하다.
//일반 fetch
fetch("www.xxx.com")
.then(response => response.json())
.catch(error => console.log(error);
//async await 사용
async function fetchUser(){
const result = await fetch("www.xxx.com");
const json = await result.json();
}
async는 반드시 function 앞에 붙여주어야 하고, await 은 async 함수 안에서만 사용이 가능하다.
await은 문자그대로 기다리는 것이다. 위의 코드로 설명하면 fetch 가 이행되기까지 기다렸다가 아래 console.log 를 출력한다.
기다리는 동안에는 다른 로직들이 돌아간다. ( async function 밖의 로직들 )
자바로 치면 스레드 같은 것이다.
예외는 async 로직안에서 try , catch 로 잡는다.
우선 이정도로만 정리.
'Develop > JavaScript' 카테고리의 다른 글
자바스크립트 - join (0) | 2022.07.11 |
---|---|
JavaScript - 비구조화 할당 (0) | 2022.06.28 |
자바스크립트 소수점 처리 ( 올림, 버림, 반올림 ) (0) | 2022.06.24 |
JavaScript - addEventListener 사용법 (0) | 2022.02.08 |
JavaScript - 백틱 <`> 에서 변수 사용방법 (0) | 2022.02.06 |